【问题标题】:W, A,S, D movement in Unity, don't know how to use new funtionsUnity中W、A、S、D运动,不知道新功能怎么用
【发布时间】:2021-05-14 23:46:12
【问题描述】:

您好,我对用于播放动画的动画控制器脚本有疑问,具体取决于按下的键

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

public class AnimationController : MonoBehaviour
{
        function UpdateAnimations()
        {
            if (Input.GetKeyDown(KeyCode.W))
            {
                animation.CrossFade("goup");
            }
            else if (Input.GetKeyDown(KeyCode.A))
            {
                animation.CrossFade("goleft");
            }
            else if (Input.GetKeyDown(KeyCode.D))
            {
                animation.CrossFade("goright");
            }
            else if (Input.GetKeyDown(KeyCode.S))
            {
                animation.CrossFade("godown");
            }

        }

    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        UpdateAnimations();
    }

它说“Component.animation”太旧了,我应该使用 GetComponent 但我不知道如何

【问题讨论】:

    标签: c# unity3d animation


    【解决方案1】:

    首先,您很可能是指void 而不是function,因为您的代码在c# 而不是unityscript(现在也早已弃用)


    然后是的,你得到的那个代码有多少年了?对Component.animationComponent.rendererComponent.camera 等内容的直接访问在几年前已被弃用^^

    正如错误已经告诉你宁愿使用例如Component.GetComponent 喜欢例如

    public class AnimationController : MonoBehaviour
    {
        // Reference this via the Inspector in Unity
        // via drag and drop. Then you don't need GetComponent at all
        [SerializeField] private Animation _animation;
    
        private void Awake()
        {
            // or as fallback get it on runtime
            if(!_animation) _animation = GetCompoenent<Animation>();
        }
    
        // Update is called once per frame
        private void Update()
        {
            UpdateAnimations();
        }
    
        private void UpdateAnimations()
        {
            if (Input.GetKeyDown(KeyCode.W))
            {
                _animation.CrossFade("goup");
            }
            else if (Input.GetKeyDown(KeyCode.A))
            {
                _animation.CrossFade("goleft");
            }
            else if (Input.GetKeyDown(KeyCode.D))
            {
                _animation.CrossFade("goright");
            }
            else if (Input.GetKeyDown(KeyCode.S))
            {
                _animation.CrossFade("godown");
            }
        }
    }
    

    【讨论】:

    • 非常感谢老兄
    【解决方案2】:

    您是如何在代码中定义“动画”的?

    您可以尝试在代码顶部添加动画引用:

    private Animation animation;
    

    在您的 Start() 或 Awake() 方法中,添加:

    // will add reference to the animation to be the Animation component
    // in this GameObject
    animation = GetComponent<Animation>();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      相关资源
      最近更新 更多