• Unity
  • Differentiating Animation Scripts of Many Children

I'm having trouble calling animations of child objects from the parent object. If I have an object "Man", to which I have a child containing the exported Spine animations "Spine GameObject (skeleton)", then I use the following code to call animation "Walk":

skeletonAnimation = GetComponentInChildren<SkeletonAnimation>();
activeTrackEntry = skeletonAnimation.AnimationState.SetAnimation(0, "Walk", true);

But what if I then have a child object called "Weapon" with its own Spine animations attached to parent object "Man"? To access the script called "Skeleton Animation" in object "Weapon" I'd think to use "GetComponentInChildren<SkeletonAnimation>()". But this will access the script component of "Man", not "Weapon". How do I specify I want to access the script attached to object "Weapon"?

Related Discussions
...

This is a generic Unity question an applies to components in general, it is not something that applies specifically to Spine.

Some ways to solve this are:

  1. Separate attributes at the parent that you can assign GameObjects to in the inspector:

    [SerializeField] SkeletonAnimation man;
    [SerializeField] SkeletonAnimation weapon;
    ...
    void Foo() {
        man.AnimationState.SetAnimation(0, "Walk", true);
        weapon.AnimationState.SetAnimation(0, "Charge", false);
    }
    
  2. Use GetComponentsInChildren<> and select them by index, Note the plural s in 'Components'.

    SkeletonAnimation[] skeletonAnimations = GetComponentsInChildren<SkeletonAnimation>(); 
    man = skeletonAnimations[0];
    weapon = skeletonAnimations[1];
    
  3. Or assign your child GameObjects via name, using Transform.Find

    Transform manTransform = this.transform.find("man");
    Transform weaponTransform = this.transform.find("weapon");
    man = manTransform.GetComponent<SkeletonAnimation>();
    weapon = weaponTransform .GetComponent<SkeletonAnimation>();
    

You will find a lot of documentation about GameObjects on the Unity forums.

Thanks for the help! Yes, I have been looking through the Unity forums and online tutorials but I hadn't been able to find a solution other than using Transform.Find, which I don't want to use because I will have many instances of this prefab object. In fact, I had already posted a similar question twice on the Unity forum over the course of a month and still have not received a response. This will be very helpful going forward, thanks again!

You're welcome. 🙂

If you have many instances of the same prefab, then I would sonner or later recommend pooling and reusing them, instead of using a create, destroy, create another.. workflow.

Aside from that, if you create a prefab ahead of time I would recommend 1. Separate attributes at the parent that you can assign GameObjects to in the inspector of the three above, since this comes with no cost at runtime.