How on Earth is my GameObject not defined?
So I'm trying to have a script refer to another script when a collision is made between the player character and a GameObject. I've written this bit of code tons of times now, all but changing the name of the variable, but it seems now I'm getting an error saying that "Spot of Light" is not defined! I have been looking at this for 20 minutes now, comparing it with scripts that have worked in the past and I don't see what I'm doing wrong! Here is the script I'm dealing with right now!
public LightScriptTrue LightScript;
public GameObject SpotOfLight;
void Awake () {
SpotOfLight = GameObject.FindGameObjectWithTag ("Spot of Light");
LightScript = SpotOfLight.GetComponent<LightScriptTrue> ();
}
Answer by TBruce · Apr 12, 2016 at 06:42 PM
@shepsaus000 I am sure that you have already done this but could you verify that the Tag exists and that the tag is set on the object in question?
Also, I would just like to mention that it is common practice to use lowerCamelCase for variable names.
Please take a look at this little piece of code that may help you solve your problem:
public LightScriptTrue lightScript;
public GameObject spotOfLight;
void Awake ()
{
if (GameObject.FindGameObjectWithTag ("Spot of Light"))
{
spotOfLight = GameObject.FindGameObjectWithTag ("Spot of Light");
lightScript = spotOfLight.GetComponent<LightScriptTrue> ();
}
else
{
LightScriptTrue[] lightScripts = this.FindObjectsOfType<LightScriptTrue>();
if (lightScripts.Length > 0)
{
// loop through list here till you find what you are looking for
// you may want to also find out why tag is not set
}
else
{
Debug.Log("No objects of type LightScriptTrue exist in scene"); // if you get here then there could be a typo or some other problem
}
}
public static T FindObjectOfType <T> (this Object unityObject) where T : Object
{
return Object.FindObjectOfType(typeof(T)) as T;
}
public static T[] FindObjectsOfType <T> (this Object unityObject) where T : Object
{
return Object.FindObjectsOfType(typeof(T)) as T[];
}
}