【问题标题】:How to Control an Animation of 3D Object Using Slider in unity如何统一使用滑块控制 3D 对象的动画
【发布时间】:2018-11-20 12:58:01
【问题描述】:

假设我们的场景中有一个 3d 游戏对象,上面有单个动画,那么我应该怎么做才能使用滑块控制它的动画,比如如果更改滑块的值,动画将根据该值播放

【问题讨论】:

    标签: unity3d animation


    【解决方案1】:

    我想您想要类似于 VideoPlayer(例如 youtube 视频播放器)但带有动画的东西。从这里开始:https://docs.unity3d.com/ScriptReference/AnimationState-time.html

    using UnityEngine;
    using System.Collections;
    
        public class ExampleScript : MonoBehaviour
        {
            public Animation anim;
            public float animationTime;// attach your slider value to this float
    
            void Update()
            {
                anim["Walk"].time = animationTime;
            }
        }
    

    【讨论】:

    【解决方案2】:

    我假设你已经用他们的动画创建了一个动画师。

    您只需要知道每次修改滑块值时都会调用回调 onValueChanged。因此,您可以在其中设置新的动画模式。

    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI; // Required when Using UI elements.
    
    public class SliderAnimator : MonoBehaviour
    {
        public Slider mainSlider;
        public Animator anim;
        public void Start()
        {
            //Adds a listener to the main slider and invokes a method when the value changes.
            mainSlider.onValueChanged.AddListener(delegate {ValueChangeCheck(); });
        }
    
        // Invoked when the value of the slider changes.
        public void ValueChangeCheck()
        {           
            //Here we set the animation            
            switch((int)mainSlider.value){
              case 0:
                //Set first animation
                anim.SetBool("FirstAnimationName", true);
                break;
              case 1:
                //Set second animation
                anim.SetBool("SecondAnimationName", true);
                break;
              default:            
                break;
            }
    
            //To avoid casting the mainSlider.value
            if(mainSlider.value >= 0 && mainSlider.value < 0.5f)
            {
                //Set first animation
                anim.SetBool("FirstAnimationName", true);
            }
            if(mainSlider.value >= 0.5f && mainSlider.value <= 1f)
            {
                //Set second animation
                anim.SetBool("SecondAnimationName", true);
            }
        }
    }
    

    【讨论】:

    • 将此脚本与动画对象或滑块附加到哪里?
    • 我收到此错误 `float' 类型的 switch 表达式无法转换为整数类型、bool、char、字符串、枚举或可空类型
    • @NoumanKhan 你可以将它附加到你想要的地方,同时你把引用放在滑块和动画师上。您应该将 mainSlider.value 转换为 int(如 (int)mainSlaider.value,因为它是一个浮点值,并且 switch 不能处理浮点数。所以转换该值,或将语句转换为 if 或其他条件
    • @NoumanKhan 我已经编辑了答案,你可以看到演员是如何工作的,并让同一个块用 if 代替 switch ^^
    猜你喜欢
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多