所以我有一个滑块,以统一的形式显示动画的当前位置,你可以移动滑块来影响动画的位置。我想要做的是在滑块上添加一个播放暂停切换按钮。
我想你可以添加切换然后将切换输出更改为1或0,然后将动画速度乘以0或1来播放或暂停动画,这也不会改变动画的速度,如果它是调整到其他地方。
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class NewAnimController : MonoBehaviour {
public Slider sliderScrubber;
public Animator animator;
public Toggle playPause;
private float speed = 1f;
private float playToggle;
public void Update()
{
float animationTime = animator.GetCurrentAnimatorStateInfo(0).normalizedTime;
Debug.Log("animationTime (normalized) is " + animationTime);
sliderScrubber.value = animationTime;
}
public void OnValueChanged(float changedValue)
{
animator.speed = speed; //This is in here to make a slider in the future that changes the speed for a prefab
animator.Play("Take 001", -1, sliderScrubber.normalizedValue);
}
public void PlayPauseToggle()
{
if(playPause.isOn)
{
playToggle = 1;
}
else
{
playToggle = 0;
}
}
public void NewSpeed(float newSpeed)
{
speed = newSpeed * playToggle;
}
}
这不起作用,我不确定为什么。 :/ 我只是以错误的方式解决这个问题吗?
对于任何需要它的人,这是工作代码。
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class NewAnimController : MonoBehaviour {
public Slider sliderScrubber;
public Slider speedSlider;
public Animator animator;
private float rememberTheSpeedBecauseWeMightNeedIt;
public void Update()
{
float animationTime = animator.GetCurrentAnimatorStateInfo(0).normalizedTime;
Debug.Log("animationTime (normalized) is " + animationTime);
sliderScrubber.value = animationTime;
}
public void ScrubSliderChanged(float ScrubSliderchangedValue)
{
animator.Play("Take 001", -1, sliderScrubber.normalizedValue);
}
public void SpeedSliderChanged(float SpeedSliderchangedValue)
{
animator.speed = speedSlider.normalizedValue;
}
public void UserClickedPauseButton()
{
if (animator.speed > 0f)
{
// we need to pause animator.speed
rememberTheSpeedBecauseWeMightNeedIt = animator.speed;
animator.speed = 0f;
}
else
{
// we need to "unpause"
animator.speed = rememberTheSpeedBecauseWeMightNeedIt;
}
}
}
答案 0 :(得分:1)
" OnValueChanged"不是一个理想的名字,因为它可以指任何东西!实际上,使用描述性名称制作两个不同的函数。让每个滑块只按照自己的惯例 - 不要将它们发送到相同的程序。
请注意,您实际上并未使用' changedValue' - 如果我没弄错,你可以删除它。不要忘记你在更改代码后必须在编辑器中重新拖动所有内容
public void ScrubSliderChanged()
{
animator.Play("Take 001", -1, sliderForScrubber.normalizedValue);
}
public void SpeedSliderChanged()
{
animator.speed = sliderForSpeed.normalizedValue;
}
关于暂停,幸运的是它不容易:
你真的不需要bool变量,只需这样就可以开始了。
如果你想要一个暂停按钮(实际上不是"切换"控制)
private float rememberTheSpeedBecauseWeMightNeedIt;
public void UserClickedPauseButton()
{
if ( animator.speed > 0f )
{
// we need to pause animator.speed
rememberTheSpeedBecauseWeMightNeedIt = animator.speed;
animator.speed = 0f;
}
else
{
// we need to "unpause"
animator.speed = rememberTheSpeedBecauseWeMightNeedIt;
}
}
TOGGLE CONTROL示例代码
注意未来的googlers,不要使用切换暂停按钮。使用UI.Button作为暂停按钮。我只将此作为如何使用切换的示例..它只是.isOn
public void UserClickedPauseToggle()
{
if ( yourToggle.isOn )
// code for when toggle is 'on'
else
// code for when toggle is 'off'
}