简体   繁体   English

从 Prefab 中的 Sprite 获取 Animator (Unity)

[英]Getting Animator from Sprite inside Prefab (Unity)

I have a Controller class which has a list of GameObjects which are indeed prefabs (in my code called turtlesTypePrefab).我有一个 Controller class 有一个游戏对象列表,这些游戏对象确实是预制件(在我的代码中称为 turtlesTypePrefab)。 As you can see here, the prefabs I use have sprites inside them with animations (what I'm saying is FirstTurtle has an animator, SecondTurtle as well and so on, and they are all part of my prefab called ThreeTurtles).正如你在这里看到的,我使用的预制件里面有带有动画的精灵(我的意思是 FirstTurtle 有一个动画师,SecondTurtle 也有,等等,它们都是我的预制件的一部分,称为 ThreeTurtles)。

在此处输入图像描述

So now in my code I want to change the value of a boolean inside one of these animators of my prefab.所以现在在我的代码中,我想在我的预制件的这些动画师之一中更改 boolean 的值。

Inside of my controller I have:在我的 controller 里面我有:

public GameObject[] turtlesTypePrefab;

And then in my update method I want to do something like:然后在我的更新方法中,我想做类似的事情:

void Update()
{

    for (int i = 0; i < turtles.Length; i++)
    {
        for (int j = 0; j < turtles[i].Count; j++)
        {
            GameObject turtle = turtles[i][j];

            if (turtle != null)
            {
                MoveTurtle(turtle, i);
                // THIS DOESNT WORK
                anim = turtle.GetComponent<FirstTurtle>().GetComponent<Animator>();
                anim.SetBool("diving", true);
            }
        }
    }
}

Any ideas?有任何想法吗?

If each turtle gameobject has its own animator component what you can do is initialize the parent animator from treeturtle gameobject GetComponentInChildren().如果每个海龟游戏对象都有自己的动画器组件,您可以做的是从树龟游戏对象 GetComponentInChildren() 初始化父动画器。

What you want to do is to access the one of the children animator via code from the parent.您要做的是通过父级的代码访问其中一个子动画师。 Here is an example这是一个例子

// this script will be attached to the parent // 此脚本将附加到父级

anim = GetComponentInChildren<Animator>();

You used this line of code which the one below:您使用了以下代码行:

anim = turtle.GetComponent<FirstTurtle>().GetComponent<Animator>();

The problem with it, is that FirstTurtle is a child gameobject not a component.问题在于 FirstTurtle 是子游戏对象而不是组件。 So you can't really get FirstTurtle as a component.所以你不能真正将 FirstTurtle 作为一个组件。 Using GetComponent() only work if you want to use the animator the gameobject you are working on.仅当您想将动画师用于您正在处理的游戏对象时,使用 GetComponent() 才有效。 So I'll suggest you use GetComponentinChildren.所以我建议你使用 GetComponentinChildren。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM