private PlayerController playerControllerScript;
// Start is called before the first frame update
void Start()
{
playerControllerScript = GameObject.Find("Player").GetComponent<PlayerController>();
}
I’m following the Junior Programmer Pathway On unity Learn. I’m trying to make several GameObjects to do different functions according to what the player collider colid with, Whenever I try to Get the player Controller Script component in the other GameObjects scripts, Unity keeps telling me “NullReferenceException: Object reference not set to an instance of an object” even though it’s not null
I Have Tried :
Checking The Tag names for Any typo
Checking That I Choose the right tag name for each game object
I copied The Unity instructor Code to my project and it gave back the same null error
Hello,
To be fair, GameObject.Find() is not a very good practice, especially with a player instance that will exist in your game at all time. It’s a slow process. In start it should be fine, but get used to not using it in any Update method.
It’s better to assign it via the component, by exposing it in public or serialized and simply dragging it into the component.
To find an object with a tag, use GameObject.FindWithTag().
For your error, it’s possible that instead of having null for the GameObject.Find(name), the error comes from GetComponent(). Does your Player object have the PlayerController component? It’s not obvious from your screen capture.
I’ll Give it a try, thanks for sharing your experience.
yes, I just checked to make sure that I didn’t forget to attach it in the player object, and it’s functional.
Happy to help ! It’s a better-suited code now to my opinion
For the GameObject.Find(), is there any reason “Player” would be inactive when Start() calls (do you activate it later?)
Is it possible that a blank space is hidden after Player name?
Do you have the same error with GameObject.FindWithTag()?
Anyway, no need to investigate much more, unless it becomes a problem later
I don’t think so because I’m using the default player tag created by unity.
I didn’t use " GameObject.FindWithTag()? " I serialized the player controller object and dragged and dropped the game object into it and it’s functional now I can access the bool I need from it.