C
C#12mo ago
Baboy

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