【问题标题】:How can I change animator variable using c# script in Unity?如何在 Unity 中使用 c# 脚本更改动画器变量?
【发布时间】:2019-07-09 15:41:12
【问题描述】:

在学习游戏开发的过程中,我决定自己做一款游戏。然而,当我通过“Animator”选项卡将我的动画放在我的模型上时,我偶然发现了一个问题。 我在动画器中创建了一个“float”类型的参数,如果速度大于或小于值 x,它会播放某个动画。但是,为了实例化步行/跑步速度,我使用了位于 Inspector 选项卡中的字段。 问题是,由于初始化的速度总是不同于 0,动画师使用插入的值并播放行走动画,尽管没有按下任何键!

我已经尝试了各种我在网上找到的东西,例如,使用动画上的“参数”复选框或使用不同的代码行,例如“animator.SetFloat("Speed", (speed));"在我的脚本上,但这些都没有奏效。

// Update is called once per frame
void Update()
{
    //animator.SetFloat("Speed", Mathf.Abs(speed));
    animator.SetFloat("Speed", (speed));

    float horizontal = Input.GetAxis("Horizontal");
    float vertical = Input.GetAxis("Vertical");

    Vector3 moveDirection = new Vector3(horizontal, 0f, vertical) * speed * Time.deltaTime;
    transform.Translate(moveDirection);

我希望输出如下: 没有按键时,播放空闲动画。 当WASD键被按下时,行走动画播放。 当按下 Shift + WASD 键时,运行动画播放。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    在您描述的情况下,您可能想要考虑完全不使用转换,而是使用 animator.Play 甚至可能使用 animator.CrossFade 进行转换的代码来完成所有操作

    public class ExampleEditor : MonoBehaviour
    {
        private Animator animator;
    
        private void Update()
        {
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                animator.Play("Running");
                return;
            }
    
            if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D))
            {
                animator.Play("Walking");
                return;
            }
    
            animator.Play("Idle");
        }
    }
    

    或者,如果您更愿意使用参数,您可以使用 bool 之类的

    public class ExampleEditor : MonoBehaviour
    {
        private Animator animator;
    
        private void Update()
        {
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                animator.SetBool("Running", true);
                return;
            }
    
            animator.SetBool("Running", false);
    
            if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D))
            {
                animator.SetBool("Walking", true);
                return;
            }
    
            animator.SetBool("Walking", false);
        }
    }
    

    并且有类似的过渡条件

    IDLE -> Running if Running=true
    IDLE -> Walking if Running=false && Walking=true
    
    Running -> Walking if Walking=true && Running=false
    Running -> IDLE if Walking=false && Running=false
    
    Walking -> Running if Running=true
    Walking -> IDLE if Walking=false
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-18
      相关资源
      最近更新 更多