getcomponent cant find every button script in every gameobject
so yesterday my code is working, but now its error. i found the problem is the unity cant find button object, i dont know why so i erase all code and make something simple like in image
but then program still print null, and the object is founded. what is wrong with my code,the name is already correct.
Try to change to Text,unity can find it, but every button is always null. what is wrong with this situation, and can i get the solution thank you :) (sorry if my english is bad)
Start by simplifying it. You declared and set mybutton but ins$$anonymous$$d of using mybutton you keep using GameObject.Find().GetComponent()
.
The problem could be the way you nullcheck. If I remember right, to check the presence of an object you use if(object)
ins$$anonymous$$d of if(object == null)
. Not got time to look up about Components and scripts; school run.
so to check null is like that :) so i try to check null and it's still null.(i relize it's still null)
my real problem still there.when i use mybutton.enabled = false, it's still nullreferenceexception.
and even when the gam is played,mybutton not filled ( i also cant drag the button to mybutton manual)
Answer by victorbisaev · Feb 01, 2018 at 08:32 PM
Try this:
1) Call GameObject btnGameObject = GameObject.Find("/Canvas/Pause_Button");
and inspect btnGameObject
so it should be not null. It checks the GameObject with this name is in the hierarchy. Notice "/" at the beginning of the string ID "/Canvas/Pause_Button"
so to perform the search from the Root.
2) When btnGameObject
is not null, perform Button btn = btnGameObject.GetComponent<Button>()
and inspect btn
is not null. It checks the "Button" component is attached to the "/Canvas/Pause_Button" GameObject.
Your code looks good so I think the problem is in the ID or missed component.
if i check the game object GameObject btnGameObject = GameObject.Find("/Canvas/Pause_Button");
unity found it, but when i perform the button Button btn = btnGameObject.GetComponent<Button>()
it's back to null.
i'am so confuse, i change to find component like Text, it's not null. only button who get null(every button in this project tbh)