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:
using UnityEngine;
using System.Collections;
public class Enable_Disable_Script : MonoBehaviour {
private cubeScript myScript;
// Use this for initialization
void Start ()
{
myScript = new cubeScript();
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown (KeyCode.Return)) {
myScript.Cube.SetActive (false);
}
else if (Input.GetKeyUp (KeyCode.Return))
{
myScript.Cube.SetActive(true);
}
}
}
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!
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;
public class CubeManager : MonoBehaviour
{
public GameObject MyCube; // Either do this and populate it in the inspector
private GameObject _myCube; //Or make it private and find it in start
public void Start()
{
_myCube = FindObjectOfType<cubeScript>().gameObject;
}
public void Update()
{
if (Input.GetKeyDown(KeyCode.Return))
{
//If using public variable
MyCube.SetActive(!MyCube.activeInHierarchy);
//If using private
_myCube.SetActive(!_myCube.activeInHierarchy);
}
}
}
Also, please use code tags when posting code. Thanks.