- Home /
Why is the Object reference is empty ?
Hello, I posted a similar question before, couldnt get an answer. What I am trying to do is a very common thing I believe, and should be easy to solve but somehow I just cant.
Whene I call an instance of script A, in script B, if I try to access its properties, I always get Object reference is null exception, which I dont understand why. Here is one of those places taht I try to do it.
void OnGUI()
{
if(GUI.Button(new Rect(10,10,100,100),"blas"))
{
CameraShooot other = gameObject.GetComponent<CameraShooot>();
if(other != null)
other.selectedTexture = (Texture)Resources.Load("ege2");
}
}
Would be really happy if someone can tell me what am I doing wrong ? Why 'other' variable seems to be null all the time ? If anyone asks, 'selectedTexture' is a Texture type public variable which is instatiated with new Texture() and all..
Thanks.
Answer by Eric5h5 · Dec 28, 2011 at 12:01 PM
If "other" is null, that means that gameObject.GetComponent<CameraShooot>();
returned null. In other words, that script doesn't exist on the gameObject.
So this mean both script A and B are have to be attached to the same object ? I didnt know that :/
So do you have any suggestion how to reach such object that is located in a script attached to another object. I will do research but maybe you have a quick answer. Thanks for the reply.
gameObject.
refers to the gameObject that the script is attached to. Substitute a different gameObject if you want to get a script on a different object.
I guess you need help with "accessing other game objects" ;)
yes, i do ineed :) i went through it once again once I realized im all confused. Now its much more clear to me. But thanks for the heads-up!
Your answer
Follow this Question
Related Questions
NullReferenceException Error 6 Answers
Instantiate() as GameObject = null reference 1 Answer
Null Reference exception error 2 Answers
Why is this code getting NullReferenceException 2 Answers
Null Reference Exception error 3 Answers