- Home /
Accessing parent gameobject script not working
Any ideas why the console keeps returning null? The parent gameobject has a script attached named "AIFollow".
private var AIFollowScript : AIFollow;
function Start () {
AIFollowScript = transform.parent.gameObject.GetComponent(AIFollow);
Debug.Log(AIFollowScript);
}
$$anonymous$$aybe this object's parent is null, too? :)
As per chainedlupine s comment
function Start () {
Debug.Log(transform.parent.gameObject);
AIFollowScript = transform.parent.gameObject.GetComponent(AIFollow);
}
Seems to grab the parent fine. Just the get component that isn't working…
In case I've made some obvious error I can't see, here's the component in the parent inspector: http://i.imgur.com/2HooP.png
@Essential Are you sure you are calling the correct gameobject? Try this debug
Debug.Log(transform.parent.gameObject.GetComponent(AIFollow));
maybe get the position as well, and pause the game and compare your 'parents' position to the printed position.
Answer by CHPedersen · May 05, 2012 at 12:21 PM
It's definitely not parent being null. If that were the case, the code would throw a NullReferenceException because you'd be trying to call GetComponent on something that was null, and that isn't the case.
This might be a shot in the dark too, but I think this is a script language thing. From the screenshot provided, it follows that AIFollow is a C# script, but the script you're calling it from is clearly JavaScript.
Please see this:
http://unity3d.com/support/documentation/ScriptReference/GameObject.GetComponent.html
And note, specifically, the sentence:
"It is better to use GetComponent with a Type instead of a string for performance reasons. Sometimes you might not be able to get to the type however, for example when trying to access a C# script from Javascript. In that case you can simply access the component by name instead of type."
This is exactly your situation. It's probably failing due to the type inspecificity of javascript versus the type safety of C#, and you're using the generic version of GetComponent in your code.
Try switching to the string version and fetch it using,
transform.parent.gameObject.GetComponent("AIFollow");
instead.
Thanks for the info, didn't know that. Gave it a try but it still isn't working…
Ah, yes it did fix it actually. I just also had another script of the same name.
Thanks!