- Home /
GameObject.Find GetComponent C#
Just wondering why this isnt working:
GameObject.Find(“first_person_controller”).GetComponent<MouseLook>().enabled = false;
everything is named correctly. I did a debug and it prints NULL so I’m not really sure what to do from here
Error message:
NullReferenceException: Object reference not set to an instance of an object
Try getting your FPC first then get it's component. Also you should be finding gameobjects by name starts with, it's better practice.
can you give a screen shot of the object you are looking for in hierarchy?
I would suggest NEVER using GameObject.Find. It is super slow and is error prone. Use Tags or have a class that keeps track of them.
@B$$anonymous$$ayne would you suggest GameObject.FindGameObjectsWithTag
Answer by WillNode · Jan 02, 2015 at 05:57 AM
try to make sure that the Game Object
( “first_person_controller”
) are active when the game trying to execute that code. this is because GameObject.Find
function only returns active Game Objects.
Answer by tanz94 · Jan 02, 2015 at 02:39 AM
First make sure first_person_controller name is same as seen in hierarchy.And then check in an if statement whether the specified component is attached to it.
if( GameObject.Find(“first_person_controller”).GetComponent()!=null)
Answer by YouBungy · Aug 01, 2018 at 06:39 PM
You Cant Just Use "Find". The Best Way Would Be To Use set a tag on the Object you want to find and use "FindWithTag" instead of "Find". Works Every time.
Uhm, what makes you think that you can't use GameObject.Find?
I guess I should say you should use. Gameobject.find is getting replaced with the new 2018 update as shoe in their live stream
Answer by cryingwolf85 · Aug 03, 2018 at 04:49 PM
I see what the problem could potentially be.
In one of the screenshots you posted, I see there's an arrow pointing down on the "first_person_controller" object, indicating it has children.
Make sure the MouseLook script is attached to the object first_person_controller and NOT its children, or else you will get a null with you current code.