Null Reference Exception
I'm trying to learn variables by following a cookie clicker guide and it says "NullReferenceException: Object reference not set to an instance of an object" I've attached the script to a separate object then referenced a textbox to the script within the object. so so confused as why its not working
16 Replies
CookieText
hasn't been set to anything in this code, so far
until it's set to something, you can't call methods on it
(as to how you do that... no idea, that's probably a unity thing)I thought CookieText was allowing me to connect a text object within unity
does cookietext have a text child
or component*
Ive applied the Script to an object called "MechanicObject" here
that then display a component on the right
then attached a text box to it which i thought would edit the text component of said text box
not sure what u mean by text child sorry im really new haha
just trying to give as much info as possible
press on Text (TMP)
and show me it in inspector
text component i meant btw
just renamed it to cookie text
im used to child, but theyre different things
is this what u mean?
ye
Its possible you shouldnt do GetComponent<Text>() but another type
not Text
try finding it in TMP docs or something thats like
TextMeshPro or something
Text is a legacy component, a much more simpler text basically
and since you do not have that component, youre getting null
you have another variation of it, offered by TMP
oh okay, so when i try to get the text component its not doing it because its something different for me?
basically, unity searches for a Text component. A class/script attached to it thats can be cast to Text (basically Text itself or a derived class)
since there is none on your gameobject, it returns null
and then youre trying to access a property on a null reference
hence null reference exception
Okay that makes perfect sense, I am following a guide from 5 years ago so its all coming together
they were most likely using legacy text
thats why
youre using TMP, a newer version, so you need to change your code accordingly
Okay thank you, i will change up some things and see how it goes ❤️
OMG IT WORKS LOVE YOU THANKS ALOT
also btw
advice from someone who first learnt unity then C#
trust me its so much more worth it to learn normal C# first
and then unity
Yeah makes sense thank you I was genuinely going to give up after 2 days but I have so much energy to carry on now haha