S
S
Slavon72021-09-02 22:59:42
Unity
Slavon7, 2021-09-02 22:59:42

How to animate a child element?

How to make an animation of a child element? The bottom line is that I have a lot of child elements and hanging animation on them is not an option. I would like to have animation in the project and through the code at startup we find a random element and hang the animation

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScrpChl : MonoBehaviour
{
    
    int max;
    public GameObject parent;
    public Animation anim;
    public AnimationClip a;

    void Start()
    {
        anim = GetComponent<Animation>();
        Debug.Log(transform.childCount);
        parent.transform.GetChild(Random.Range(0, transform.childCount + 1)).gameObject.anim.Play(a.name); // не понимаю как правильно записать gameObject.anim.Play(a.name);
    }
   
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
pashara, 2021-09-03
@pashara

I did not modify the code qualitatively in any way, only logically:

void Start()
    {
        anim = transform.GetChild(Random.Range(0, transform.childCount)).gameObject.GetComponent<Animation>(); //Изменил диапазон рандома
        Debug.Log(transform.childCount);
       anim.Play(a.name);
    }

First you need to select a random element with an animator, get an animator from this element and only then
start the animation (in the question code it is not clear what is happening - the GameObject'a takes a field that is not originally in Unity.).
PS Such code is dangerous, because there are a lot of moments where it can easily catch nullreference
PSS This script is hung up on the parent. The parent selects the element on which to run the animation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question