C
C#6mo ago
I Nemo bread

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 sadge
16 Replies
ChucklesTheBeard
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 Nemo bread
I Nemo bread6mo ago
I thought CookieText was allowing me to connect a text object within unity
Developful
Developful6mo ago
does cookietext have a text child or component*
I Nemo bread
I Nemo bread6mo ago
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
Developful
Developful6mo ago
press on Text (TMP) and show me it in inspector text component i meant btw
I Nemo bread
I Nemo bread6mo ago
just renamed it to cookie text
Developful
Developful6mo ago
im used to child, but theyre different things
I Nemo bread
I Nemo bread6mo ago
is this what u mean?
Developful
Developful6mo ago
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
I Nemo bread
I Nemo bread6mo ago
oh okay, so when i try to get the text component its not doing it because its something different for me?
Developful
Developful6mo ago
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
I Nemo bread
I Nemo bread6mo ago
Okay that makes perfect sense, I am following a guide from 5 years ago so its all coming together
Developful
Developful6mo ago
they were most likely using legacy text thats why youre using TMP, a newer version, so you need to change your code accordingly
I Nemo bread
I Nemo bread6mo ago
Okay thank you, i will change up some things and see how it goes ❤️ OMG IT WORKS LOVE YOU THANKS ALOT
Developful
Developful6mo ago
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
I Nemo bread
I Nemo bread6mo ago
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