我有一个脚本,根据slowMotionTimeLeft
更新滑块值,以减少slowMotionTimeLeft
。我正在使用一个带有协程的for循环,延迟为1秒,如下所示:
IEnumerator DecreaseSlowMotionTime()
{
for(int i = 0; i < 5f; i++)
{
slowMotionTimeLeft -= 1f; // decrease slow motion
///<summary>
/// if slow motion time is less than or equal to 0 break the loop
/// </summary>
if (slowMotionTimeLeft <= 0f)
{
onSlowMotion = false;
break;
}
yield return new WaitForSecondsRealtime(1f); // delay
}
}
现在我有一个滑块,我想基于slowMotiontimeLeft
平滑地更新该值,但它不光滑,它像协程一样每秒更新,我试图修改值,但它不起作用。脚本如下:
// Slow Motion Bar
[Header("Slow Motion Slider Bar")]
[SerializeField] private Slider slowMoLeft;
[SerializeField] private float slowSliderSmoothSpeed = 0.125f;
// Other
private Player playerScript;
void Awake()
{
playerScript = FindObjectOfType<Player>();
}
void Update()
{
UpdateSlowMoSlider();
}
public void UpdateSlowMoSlider()
{
slowMoLeft.value = playerScript.slowMotionTimeLeft;
}
有什么建议吗?我需要更新协程计时器使等待0.1秒吗?
我会在Update:
// Remove the IEnumerator DecreaseSlowMotionTime(), instead add this, or if you already use Update() add the content of this method to Update()
public void Update()
{
if (slowMotionTimeLeft > 0)
{
slowMotionTimeLeft -= 1f * Time.deltaTime;
}
}
// Slow Motion Bar
[Header("Slow Motion Slider Bar")]
[SerializeField] private Slider slowMoLeft;
[SerializeField] private float slowSliderSmoothSpeed = 0.125f;
// Other
private Player playerScript;
void Awake()
{
playerScript = FindObjectOfType<Player>();
}
void Update()
{
slowMoLeft.value = playerScript.slowMotionTimeLeft;
}
你可以让你的代码更好:
您可以这样做,而不是每秒更新一次slowMotionTimeLeft
:
IEnumerator DecreaseSlowMotionTime()
{
while (onSlowMotion)
{
// decrease slow motion without considering Time.timeScale
slowMotionTimeLeft -= Time.unscaledDeltaTime;
// if slow motion time is less than or equal to 0 break the loop
if (slowMotionTimeLeft <= 0f)
{
onSlowMotion = false;
}
// will execute again in the next frame
yield return null;
}
}
然后你的滑块将以1:1的速度平滑地减少。
我知道另一种方法只要下载DoTweenModuleUI就可以了https://github.com/fisheraf/Stroids/blob/master/Stroids/Assets/Demigiant/DOTween/Modules/DOTweenModuleUI.cs
将此脚本保存在任意外部插件文件夹中,然后使用
yourimageName.DoFillAmout (TargetValue、持续时间);就是这样比如这个imageSlider。DOFillAmount(迫害elixir/10,0.5 f);