How do I resolve NullReferenceException ??
I'm trying to access a public variable from another script and I'm getting a NullreferenceException.
I've searched for and read many of the 150+ pages on the issue and I think I can get around it with a "FInd" but I'm having a hard time with the syntax...I can't find any examples that are on point with the syntax I need.
Here's the Variables I want to access:
public class GameVars : MonoBehaviour
{
public int RedStrength;
public int BlueStrength;
}
BUT...when I try to access them from another script I get the null reference error.
Here is one example of the "Find" I've tried in another script...and I've tried different combination/variations of syntax from LOTS of "answers" but none seem to be what I need.
void Awake()
{
GameObject go = GameObject.Find ("BlueStrength");
go.GetComponent<GameVars> ().BlueStrength;
}
ODDLY...I was able to access this variable from the other script for awhile (without using any sort of "find") but then I must have changed something that triggered the Null Exception error and now even though I've tried to replicate the problem free code I still get the error.
Thanks in advance for any help.
Funny thing...I'm continuing to do searches on this matter to attempt to find a solution...I finally found one in a search that, at last, seemed exactly on point and I opened it with great hope of finding a resolution...
...only to find that it was my very own question I just posted a few $$anonymous$$utes earlier.
Okay, well, I guess you had to be there. :-)
Answer by Cuttlas-U · Aug 14, 2017 at 04:47 PM
hi;
try to find it by the type of it and not with name like this :
GameObject.FindObjectOfType<GameVars>().BlueStrength;
======================
so what are u doing in this lane ?
go.GetComponent<GameVars> ().BlueStrength;
u are just getting an access to an int but not doing any thing or assign it to another int ;
Thanks. I was trying to assign it values at the same time or immediately after I tried to find it but I was still getting the NullException error. In fact, I assigned it values in the script "GameVars" and then tried to access/change those values but I still get the NullException error.
I was trying to FIRST "find" it somehow so I could access/assign/change its value but I can't figure out the syntax to "find" it.
I'm still getting errors...I'm not figuring out exactly what I need to do and even if I knew whether to use the "Find" or "FindObjectOfType" I'm still not sure of the syntax and I can't seem to find it anywhere.
Still not working. I'm still looking up stuff and trying different things off an on.
I figured it out based on what you wrote above. At first, I didn't fully understand it. But after I looked more thoroughly, I finally got what you were saying.
Thanks.