- Home /
NullReferenceException while trying to access script on object
Hello,
I've a script attached to a gameobject, this script called "testvar.cs" and contains:
public int great = 123;
Now I need to change "great" value from 123 to 2, from another script, and I'm using this line:
playerPrefab.GetComponent<testvar>().great = 2;
playerPrefab is a the public gameobject (set with the inspector)where I've "testvar.cs" script. By the way that line of code always produce NullReferenceException.
Where is the error ? Thanks
Pull it apart to test what is going on:
if (playerPrefab == null)
Debug.Log("null playerPrefab");
if (playerPrefab.GetComponent() == null)
Debug.Log("GetComponent on testvar" failed");
Post the initialization code for playerPref. If you initialize it in the inspector, check to make sure that the script above is not attached to multiple game objects.
This is what I get:
GetComponent on testvar failed
The strange thing is that the intellisense find the "great" variable ! :(
EDIT: also yes, testvar.cs is attached to other objects, but I need to modify only the one attached to playerPrefab game object !!
Intellisense will find the "great" variable because the function is returning an object which would contain it if not null
. It seems like your "playerPrefab" does not contain the "testvar" component :)
O$$anonymous$$ I FOUND IT: if I put the testvar.cs script in the root of the gameobject it works, but if I put the script in a sub gameobject, then it doesn't work. How can I fix this ? I need the script in a sub gameobject :/
Oh! Well then you need to use
GetComponentInChildren<testvar>()
ins$$anonymous$$d. Just 'GetComponent' only returns components on that specific object.
Answer by Luca91 · Jun 03, 2013 at 07:53 PM
FIXED :D
I've read that Unity 4 handles active totally different, so I fixed it using:
playerPrefab.GetComponentsInChildren<testvar>(true)[0].great;
Thanks :D
Answer by darthbator · Jun 03, 2013 at 06:40 PM
If you want to get an object on a child by targeting the parent object you would want to call FindComponentInChildren
It doesnt work :( if I run this code:
if (playerPrefab.GetComponentInChildren<testvar>() == null)
Debug.Log("GetComponentInChildren on testvar failed");
I get:
GetComponentInChildren on testvar failed
Damn :/
Your answer
