- Home /
"GetComponentInParent" - How do I do it?
Have been looking for an easy way get a Component looking the other way than in the children, but there seems to be no easy way? Have I missed somthing in the documentation, or is there only the hard way to do it? (ps. I made up GetComponentInParent, since it was the easiest way to explain my problem)
Answer by burnumd · Aug 30, 2010 at 09:48 PM
Try
transform.parent.GetComponent<YourComponent> ()
(where, obviously, "YourComponent" is your component). If you want to search from the top down of your object, you can also get
transform.root.GetComponentInChildren<YourComponent> ()
Both "parent" and "root" are members of the Transform class which you should have access to if your class extends MonoBehaviour. The latter would be a pretty intense operation for frame-by-frame updates, but would suffice for caching in Awake()
/Start()
.
Answer by Lasse-Loepfe · Jun 05, 2014 at 01:29 PM
Since Unity 4.5, you can directly call GetComponentInParent()
Docs are here:
http://docs.unity3d.com/ScriptReference/Component.GetComponentInParent.html
Note: helpfully GetComponentInParent
will look at all parents (e.g. in the parent of parent). And there is also a GetComponent*s*InParent function.
Answer by Tabu · Aug 30, 2010 at 08:32 PM
Ok, I feel a bit stupid, but it still might not be the best way to do it. But this is how I did it: I have two scripts, WeaponScript and MovementScript, the WeaponScript is in a childHieracy below the MovementScript. So I start out in the MomentScript finding the WeaponScript, then in the WeaponScript I make a function where I can push the MovementScript.
MovementScript takeout:
void Start()
{
myWeapon = (WeaponScript)this.GetComponentInChildren<WeaponScript>(); //Here i get the WeaponScript
myWeapon.setMovementScript(this); //Push this script into the Weaponscript
}
WeaponScript TakeOut:
private MovementScript moveScript; //Makes a MovementScript variable.
public void setMovementScript(MovementScript x) // This is the function called in movementscript. { moveScript = x; }
I will still absolutely like to hear about alternatives to this way of dooing it, as I am not completly sure this is the best way to do it!