Accessing GameObject just will not work?

I have a game object named AppManager and attached to this is a script named AppManagerScript

From another script I run this in Start() and have also tried in Awake()

appManager = GameObject.Find (“AppManager”);

But all I get is the error
NullReferenceException: A null value was found where an object instance was required.

I have deleted all the code for this and the game object a number of times and recreated and yet still no joy?

Any help please?

What’s the code where you access this object?

appManager.GetComponent ().DidFindTarget ();

Hm, I won’t be able to help you more without seeing your project file. I suspect a typo in the name, or the object is being destroyed or is not created yet at the time that .Find is being run. I can suggest an alternative approach that’s generally more reliable: The singleton.

//AppManagerScript
public class AppManagerScript : MonoBehaviour {
public static AppManagerScript main {
get {
//optional: if _main is null, then create a new instance here, and assign it to _main
return _main;
}
}
private static AppManagerScript _main;
void Awake() {
_main = this;
}
}

//anywhere else
AppManagerScript.main.DidFindTarget();

This will work for any script where there needs to be just one copy in the scene. It’s both faster and more reliable than using GameObject.Find and GetComponent (it will survive renaming a GameObject, for example).

If you try this approach and the problem persists, then at least we will have narrowed it down - we will know that the object does not exist at all, rather than that it just isn’t being found.

1 Like

Thanks for the concise reply and the excellent code, really appreciate it.

Works perfect :):):slight_smile: