- Home /
Referencing an Animator component from a parent object?
Hi, I'm trying to reference an animator which does all the animations for a player's weapon, including:
Aiming down sights
Movement
Reloading
Firing
I want to do this from a scrip attached to the player since this script controls when the player can fire and reload, how much ammo to load, etc.
I am using JS
How do I do this? Feel free to ask questions for more info. Cheers.
Answer by Cherno · Jul 06, 2015 at 09:40 AM
You can use GetComponentInChildren or GetComponentsInChildren to create a reference to a component that is attached to a child object.
How would I use this and Would it have to be used every time I referenced something in relation to the Animator?
For example I have
animator.SetFloat ("Walk", v);
animator.SetFloat ("Turn", h);
animator.SetFloat("Sprint", sprint);
would it have to be:
GetComponentInChildren(Animator.animator.SetFloat ("Walk", v));
GetComponentInChildren(animator.SetFloat ("Turn", h));
GetComponentInChildren(animator.SetFloat("Sprint", sprint));
(Sorry if that's the incorrect referencing :S)
The linked pages provide example on how to use the function. If you need to access the component more than once, then it is recommended to create a seperate variable that will hold the reference.
private var animator : Animator;
function Start() {
animator = GetComponentInChildren(Animator);
}
function SetAnimatorFloats() {
animator.SetFloat ("Walk", v));
animator.SetFloat ("Turn", h));
animator.SetFloat("Sprint", sprint));
}
Thanks,How do I tell it which animator to use if there are multiple children, each with their own animator? I need to reference specific animators in specific children.
I recommend declaring variables for each of the child animators then. If they won't change at runtime, it's erasiest to just assign them via the inspector, otherwise you have to use GetComponentsInChildren to return all Animator componenets in the parent object's hierarchy, iterate through the returned array, and somehow assign the right animators to the right variable; you would have to find a way to differentiate between them, for example giving them specific names, tags, or whatever.
private var animator : Animator;
public var animator_child1;//Drag the child onto this field in the inspector
public var animator_child2;//Drag the child onto this field in the inspector
function Start() {
animator = GetComponentInChildren(Animator);
}