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!
A couple things right off the bat… first off, use the code tags when putting in code, it makes it much more readable. Now, onto your problem. Obviously, as we know, when a GameObject is deactivated, all of it’s components are as well. So, as you’ve already done, somewhere else we should put the script that controls the activation and deactivation for the cube. Somewhere like the Camera could be good as that will always be there.
Now why isn’t it working? Why exactly are you instantiating a new cubeScript in the Start method? We don’t want to instantiate a new script, we want to find the script on the GameObject of the cube we want to turn off. This can be done in a number of ways. You can use:
GameObject.Find("NAME OF GAMEOBJECT").GetComponent<YOURSCRIPT>();
OR
you could always just make the myScript variable public and from the inspector just drag the targeted cube into that field.
Now, once you get a reference to the targeted GameObject, you can easily turn it off and on with an easy method like this:
void ToggleEnabled() {
targetCube.SetActive(!targetCube.activeSelf);
}