Search Unity

How to store a gameobject in a variable

Discussion in 'Scripting' started by Amaan-Sadri-Wala, Jun 10, 2017.

  1. Amaan-Sadri-Wala

    Amaan-Sadri-Wala

    Joined:
    Jun 9, 2015
    Posts:
    14
    I have a script attached to a cube in my project, I want to activate and deactivate the cube when I press return and shift key respectively, but I can't do that in the script attached to the object as once the object is disabled, the script can't be accessed anymore, so I created another cube and attached a script to it, I put in this code:

    1. using UnityEngine;
    2. using System.Collections;
    3. public class Enable_Disable_Script : MonoBehaviour {
    4. private cubeScript myScript;
    5. // Use this for initialization
    6. void Start ()
    7. {
    8. myScript = new cubeScript();
    9. }
    10. // Update is called once per frame
    11. void Update ()
    12. {
    13. if (Input.GetKeyDown (KeyCode.Return)) {
    14. myScript.Cube.SetActive (false);
    15. }
    16. else if (Input.GetKeyUp (KeyCode.Return))
    17. {
    18. myScript.Cube.SetActive(true);
    19. }
    20. }
    21. }
    NOTE: cubeScript is the script I attached to the first cube

    My question is - How can I store the cube(gameobject) that I want to activate/deactivate in a variable?

    Please help, I am a beginner in unity and I don't know how to do this, any help will be appreciated!
     
    Mike2699 likes this.
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    Either make a global public gameobject variable in your your script which isn't attached to the cube (it can be in an empty gameobject btw) and drag your cube gameobject into that variable in the inspector or use a private global variable and find the cube.

    Like so;

    Code (CSharp):
    1. public class CubeManager : MonoBehaviour
    2. {
    3.     public GameObject MyCube; // Either do this and populate it in the inspector
    4.  
    5.     private GameObject _myCube; //Or make it private and find it in start
    6.  
    7.     public void Start()
    8.     {
    9.         _myCube = FindObjectOfType<cubeScript>().gameObject;
    10.     }
    11.  
    12.     public void Update()
    13.     {
    14.         if (Input.GetKeyDown(KeyCode.Return))
    15.         {
    16.             //If using public variable
    17.             MyCube.SetActive(!MyCube.activeInHierarchy);
    18.             //If using private
    19.             _myCube.SetActive(!_myCube.activeInHierarchy);
    20.         }
    21.     }
    22. }
    Also, please use code tags when posting code. Thanks.
     
  3. Amaan-Sadri-Wala

    Amaan-Sadri-Wala

    Joined:
    Jun 9, 2015
    Posts:
    14
    T
    Thank you very much for the help!
    And yeah, I will remember the code tags!
     
    Last edited: Jun 10, 2017