NullReferenceException error, GameObject.Find.

Hey, i'm getting the "NullReferenceException" error using this code:

var go4= GameObject.Find("Player4-Name");
var go4lvl2 = GameObject.Find("Player4-lvl2-Name");

go4.GetComponent(GUIText).text = name4; //<--- ON THIS LINE
go4lvl2.GetComponent(GUIText).text = name4;

The code is placed inside Update(); function, and both "Player4-Name" and "Player4-lvl2-Name" exsists. Cheers!

Well, you should learn to debug your code. That are tiny common errors and they are easy to spot since there are only a few sources. Try to put a Debug.Log("Is Player4-Name there? "+(go4 != null)); right after your GameObject.Find. If it is found it should return "true". Same goes for the GUIText but that you can check in the inspector much easier ;) Make sure your GO name matches exactly the search string. One different or additional character and it can't be found.

1 Answer

1

Is there a GUIText attached to the GameObject Player4-Name (and Player4-lvl2-Name)?

Maybe it is missing this component.