- Home /
Unity can't find gameobject from C# script. How can I solve this?
In C# Script, I write " Public GameObject Time01" and I have a gameobject in unity. but when I play the game , there occurs errors about Time01 is undefined. How can I define my GameObject. Please help. Here I share my code. The code is about time decreasing after play the game.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class Timer : MonoBehaviour { public GameObject Time01; public bool istakingtime = false; public int seconds;
void Update()
{
if (istakingtime == false)
{
StartCoroutine(SubtractSecond());
}
}
IEnumerator SubtractSecond()
{
istakingtime = true;
seconds -= 1;
Time01.GetComponent<Text>().text = "" + seconds;
yield return new WaitForSeconds(1);
istakingtime = false;
}
}
$$anonymous$$ake sure that Time01
is set in the editor (Fills the applicable box on the $$anonymous$$onoBehaviours script).
Answer by I_Am_Err00r · Jul 25, 2019 at 01:24 PM
You still have to make a reference to the GameObject, just having it in your Assets folder isn't enough for the game to know what Time01 is.
If you have it set to public then select that object in the hierarchy (or prefab), look in the inspector and you should see a box that you can drag a GameObject into for that reference: It should look something like this
Just drag your time01 into that box and it will set the reference.
Your answer
![](https://koobas.hobune.stream/wayback/20220612205505im_/https://answers.unity.com/themes/thub/images/avi.jpg)