- Home /
Having trouble referencing a script
Can anyone tell me why I get an error from the following code? I'm trying to reference a C# script (from another C# script in the same project) called HazardSpawner. I'm trying to de-activate it...
HazardSpawner hazardSpawner;
void Awake ()
{
hazardSpawner = GetComponent <HazardSpawner> ();
hazardSpawner.enabled = false;
}
EDIT: here is the resulting error:
NullReferenceException: Object reference not set to an instance of an object PlayerHealth.Awake () (at Assets/Scripts/PlayerHealth.cs:28)
Whats the code at line 28 of PlayerHealth.cs ? Also , moving hazardSpawner.enabled = false;
outside of awake might work.
Answer by sumeeton · Mar 30, 2015 at 05:02 PM
They are on the seperate objects. Use the following:
GameObject.Find("HazardSpawner").GetComponent<HazardSpawner>().enabled = false;
The script you are using is searching the script component on the same gameobject.
Blimey I'm stupid. I never realised I hadn't specified the script in the inspector. Thanks
Answer by cloud4197 · Mar 30, 2015 at 04:02 PM
Sorry. Should've added that to the post.
Here it is:
NullReferenceException: Object reference not set to an instance of an object PlayerHealth.Awake () (at Assets/Scripts/PlayerHealth.cs:28)
No good I'm afraid.
The weird thing is I'm using the same method to reference another script and that's working fine:
Player$$anonymous$$ovement player$$anonymous$$ovement;
void Awake ()
{
player$$anonymous$$ovement = GetComponent <Player$$anonymous$$ovement> ();
}
void Death ()
{
player$$anonymous$$ovement.enabled = false;
}
Is the HazardSpawner script attached to the game object? If it is a prefab, then check if the prefab has the HazardSpawner script attached to it.
It's attached to an Empty Object within the hierarchy. The object has a transform and the script attached and nothing more. It's job is to instantiate random objects falling from the sky in random places at regular intervals.
Try moving the PlayerHealth script below the HazardSpawner script in the inspector. Also can you share the screenshot of the inspector when this empty object is selected?
Your answer
![](https://koobas.hobune.stream/wayback/20220613191657im_/https://answers.unity.com/themes/thub/images/avi.jpg)