- Home /
Why is reference to script object == null?
Greetings;
In C#, I have the following script:
TweenRotation _tweenRotation;
void Start() {
_tweenRotation = GetComponent<TweenRotation>();
if (_tweenRotation == null) {
print ("can't find _tweenRotation");
}
}
void OnClick_btnSettings(){
// this works just fine
_tweenRotation.enabled = true;
}
This returns null. However, I can access the script just fine. The documentation from the following URL states this:
http://docs.unity3d.com/Documentation/ScriptReference/GameObject.GetComponent.html
"function GetComponent (type : Type) : Component Description Returns the component of Type type if the game object has one attached, null if it doesn't. You can access both builtin components or scripts with this function."
Why is the object comparable to null if the object is valid and I can access the object just fine from within code?
Well, I would guess that the TweenRotation class might implement the == operator and the equals function. That way you can pretend that the object doesn't exist. That's usually done for internal types that you shouldn't be able to access. However it's not a nice workaround.
Have you tried to access the reference right after the GetComponent call?
Answer by clunk47 · Dec 26, 2012 at 10:41 PM
Try something like this. Check if the Component is found before assigning it.
TweenRotation _tweenRotation;
void Start()
{
if(GetComponent<TweenRotation>())
_tweenRotation = GetComponent<TweenRotation>();
else
print ("can't find _tweenRotation");
}
This gives the same result but because the assignment is hidden in the true clause, now I can't use the objects functions. I'm still confused as to why the object is returning as null but also usable at the same time. There is definately a C# script attached to this game object titled TweenRotation when this code is called.
Ok, I'm confused. I can access the script functions using just the delcaration of type:
TweenRotation _tweenRotation;
However, the program prints "can't find _tweenRotation". So I'm sure that
_tweenRotation = GetComponent<TweenRotation>();
is never called.
Why is the line in my buttons OnClick still working?
_tweenRotation.enabled = true;
Well, for instance in javascript i think this would work on uninitialized variable. So maybe ins$$anonymous$$d of declaring a property try reading it. This will tell you for sure wheather you have reference or not.
Answer by Bunny83 · Dec 27, 2012 at 12:12 AM
Well, it's also possible that you assign the variable elsewhere. To find out where your _tweenRotation get assigned, just turn it temporary into a property:
TweenRotation internal_TR = null;
TweenRotation _tweenRotation
{
get{ return internal_TR; }
set
{
Debug.Log("new value :" + value);
Internal_TR = value;
}
}
Now you can see in the console how often a new value is assigned and thanks to the stack trace you see from where it's assigned.