将旧的Unity代码升级到Unity 5
在触发按钮上播放动画的代码似乎不起作用。 我在Youtube上看到了一个video,并带有一个简单的animation.Play();
它适用于那个video但是,我无法让它在我的电脑上工作。 我做错了什么或团结改变了什么? 请帮助我无法在网上找到解决方案。 所有“解决方案都不起作用”。
这是我得到的错误:
类型
UnityEngine.Component
不包含播放定义,也没有扩展方法可以找到UnityEngine.component
类型的Play
using System.Collections; using System.Collections.Generic; using UnityEngine; public class animationtrigger : MonoBehaviour { void Start() { } int speed = 10; // Update is called once per frame void Update () { if (Input.GetKeyDown("N")) { animation.Play("Cube|moving side"); //transform.Translate(1 * Vector3.forward * Time.deltaTime * speed); //Animator anim = GetComponent(); //if (null != anim) // { // anim.Play("Cube|moving side"); // } } } }
我做错了什么或团结改变了什么?
团结改变了。 过去几周我见过类似的问题。 虽然我不认为它们是重复的但是在这里回答所有这些以便将来的问题是有意义的。
animation
变量在Component
下定义为MonoBehaviour
inheritance的public
变量。 然后您的代码inheritance自MonoBehaviour
,您可以访问animation
。
这些是不推荐使用的Component
类中的完整变量列表:
public Component animation { get; } public Component audio { get; } public Component camera { get; } public Component collider { get; } public Component collider2D { get; } public Component constantForce { get; } public Component guiElement { get; } public Component guiText { get; } public Component guiTexture { get; } public Component hingeJoint { get; } public Component light { get; } public Component networkView { get; } public Component particleEmitter { get; public Component particleSystem { get; } public Component renderer { get; } public Component rigidbody { get; } public Component rigidbody2D { get; }
访问附加到同一脚本的组件的新方法 :
使用GetComponent
。 将该变量的第一个字母大写,使其成为组件类。 一个例外是音频变为AudioSource
而不是Audio。
1 。 animation.Play("Cube|moving side");
变为GetComponent
2 。 GetComponent
变为GetComponent
3 。 GetComponent
变为GetComponent
4 。 renderer.material
变为GetComponent
5 。 particleSystem.Play()
变为GetComponent
6 。 collider2D.bounds
变为GetComponent
7 。 collider.bounds
变为GetComponent
8 。 audio.Play("shoot");
成为GetComponent
9 。 camera.depth
变为GetComponent
我没有把它们全部放在一起,因为下面的例子应该指导任何人这样做。 这些是SO上提问和询问最多的组件。
缓存组件 :
您可以缓存组件,这样您每次都不会成为GetComponent。
Animation myAnimation; void Start() { //Cache animation component myAnimation = GetComponent(); } void Update() { if(somethingHappens) { //No GetComponent call required again myAnimation.Play("Cube|moving side"); } }
如果您正在使用动画师并且想要播放特定状态,那么您可以:
animator.Play("stateName");
我在下面的评论代码中看到了这一点。 这应该是有效的。 如果没有发生任何事情,请确保“Cube | moving side”是STATE名称而不是ANIMATION名称。 还要确保状态实际包含动画,并且动画实际上具有帧数据。
(下面,我有2个状态(Move和Idle)。状态名称是“Move”,而动画名称是“test”。)
如果我想切换到移动状态,我会调用animator.Play(“移动”) 。
此外,我不建议明确地播放状态。 如果你可以管理它通常更好地制作状态树并使用参数触发动画。 您在上图中看到我之间有两种状态和转换。 您可以指定可以使我的动画师从一个切换到另一个的参数。
在这里,我使用“示例动画触发器”使动画师从空闲状态切换到移动状态。 我可以在代码中执行此操作:
animator.SetTrigger("ExampleAnimTrigger");
这是使用Unity动画的更现代的方式,所以我强烈建议选择它。
这是文档!