ninjachicken1
ninjachicken1

Reputation: 187

Get a child object to copy the animation of the parent in Unity

I'm trying to animate an object (a body) with multiple child components (clothes) that are designed to animate alongside the parent using identical animation controllers to the parent, but the code framework we're using is designed to only handle one animation controller and is too complex to rework to our needs in the timeframe we want it done. The result is the torso runs, but the clothes remain static.

The quick and dirty solution I'm trying to use is to use a script to read the parent's animation state and tell the child objects to copy that state, but I'm not sure how to go about this. Does anyone know how I should do this? I've considered either using a script attached to the parent or one attached to each child object, but I'm not sure what the correct approach is.

Upvotes: 0

Views: 1983

Answers (1)

Ben Rubin
Ben Rubin

Reputation: 7341

I'm doing something similar, where I have a parent object which is a character in my game, and it has a bunch of child objects for its clothing, hair, etc. Each object's animation controllers have the same named parameters.

I have this script attached to the "parent" object (the character). Then instead of calling GetComponent<Animator>().SetInteger(...) on the parent, I call GetComponent<AgentAnimator>().SetInteger(...), and that handles setting the parameters on the parent and its direct children. If your parent object has grandchildren or deeper descendants, then you'll have to update this script to read further down the descendant tree (or use could attach AgentAnimators to your children, and use the same scheme to deal with any level of children).

public class AgentAnimator : MonoBehaviour
{
    public void SetInteger(string id, int value)
    {
        Animator animator = GetComponent<Animator>();
        animator.SetInteger(id, value);
        var childComponents = GetComponentsInChildren<Animator>();
        foreach (var child in childComponents)
        {
           child.SetInteger(id, value);
        }
    }

    // Do the same for SetBool, SetTrigger, etc.
}

Upvotes: 1

Related Questions