I have a gameobject called Starting containing one Square and a legacy Text
The square serves as a button with the text saying "Press Start Button". The user will press the start button (mapped to spacebar). This will set the Starting gameObject to inactive. The code is as follows:
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (CharacterController.started == false)
{
CharacterController.started = true;
gameObject.SetActive(false);
}
else if (CharacterController.started == true)
{
CharacterController.started = false;
gameObject.SetActive(true);
}
}
}
CharacterController.started is a boolean for another gameObject.
I understand the GameObject.find() does not work if the gameObject has been set as inactive. I tried to find the GameObject from the CharacterController script like so:
void Update()
{
if (started)
{
if (Input.GetKeyDown(KeyCode.Space))
{
starting = GameObject.Find("Starting");
starting.SetActive(true);
}
}
}
This did not work and gives the error:
NullReferenceException: Object reference not set to an instance of an object CharacterController.Update () (at Assets/CharacterController.cs:33)
I am new to Unity. How do I get the Starting GameObject and set is as active?
CodePudding user response:
You have basically answered your question, the GameObject "Starting" is inactive, so it will not find it. Try referencing it at the start of your game on the CharacterController, like so:
public GameObject startingObject;
private void Start(){
startingObject = GameObject.Find("Starting"); //Find it here, or drag it into the hierarchy
}
then delete this line from the Update():
starting = GameObject.Find("Starting");
since it is bad practice to use GameObject.Find() inside the Update method anyway. It is also more preferable to reference Components to the hierarchy than using GameObject.Find(""), if possible of course, but both solutions should work fine
CodePudding user response:
Try declare it manually insted of GameObject.Find().
ex:
public GameObject starting;
then use it into Update()
void Update()
{
if (started)
{
if (Input.GetKeyDown(KeyCode.Space))
{
starting.SetActive(true);
}
}
}
Add the script to the object you wanted and drag and drop the Starting into the Script field. This is better when you have already the objects in the scenes or to instantiate a prefab from the storage.