c# - animation.Play() 不起作用

标签 c# unity3d

我很确定

animation.Play("DoorOpen");

会播放动画“DoorOpen”,但是当我试图将它放入我的代码中时,它只是给我一条错误消息:

The Animation attached to this GameObject (null if there is none attached).

using UnityEngine;
using System.Collections;

public class DoorPhysics : MonoBehaviour {

    int Open = 0;

    // Update is called once per frame
    void Update() {


        if (Open == 0) {

        if (Input.GetKeyDown("e")) {

                animation.Play("DoorOpen");

        }
    }

    }
}

最佳答案

您需要统一显示游戏对象的位置,它们彼此不认识,您必须始终使用:

GameObject.GetComponent<T>()
GetComponentInParent<T>()
GetComponentInChildren<T>()

最佳实践是在 Start() 获取对象引用 您还应该将重要!!!动画组件附加到此脚本附加到的对象

 public class DoorPhysics : MonoBehaviour {

        public Animation animation;
        int Open = 0;



    void Start()
    {
        animation=GameObject.GetComponent<Animation>(); //if your have derived type change Animation to good class DoorAnimation for example
    }

    void Update()
    {
      if (Open == 0) {
            if (Input.GetKeyDown("e")) {
                     this.animation.Play("DoorOpen");
            }
        }
    }
  }

如果该代码不起作用,您需要向我展示您的 GameObject 层次结构

enter image description here

如果您只是用它开始您的旅程,请学习 MonoBehaviour call orderlife cycles of events

关于c# - animation.Play() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33597101/

相关文章:

c# - 为什么我的 winform 在打开 Access 数据库 (.accdb) 时会调整大小,我该如何解决?

ios - 使用未声明的标识符 UIApplicationOpenSettingsURLString

c# - 如何更改.NET应用程序的预定义userconfig目录?

c# - IIS/.Net 只允许对给定用户 session 的单个并发响应

c# - 根据存储的时区修改 ASP.NET MVC C# 中的日期

c# - 跟踪 SQL Server 中创建和更新时间的最佳方法

c# - Unity5中的函数更新在函数启动后不接收变量的值

c# - 在 UI 文本组件上显示控制台日志

facebook-graph-api - Facebook Unity3d SDK 不包含 FBUtil 和 GameStateManager 类

c# - 下载硬盘中的AssetBundle