Unity 3d 调用重复用于闪烁图像



我正在做一个汽车游戏项目。我制作了一个UI面板,其中有两个UI图像(Left_Image和Right_Image(。当我按下"左"按钮时,Left_Image开始闪烁,当我按下"右"按钮时,Right_Image开始闪烁。但我想要的是,如果Right_Image已经闪烁并且我按下"左"按钮,那么Left_Image开始闪烁,但应该停止Right_Images。我已经尝试了所有技巧,但没有运气。请帮忙。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Indicators_UI : MonoBehaviour {
public GameObject flash_right;
public GameObject flash_left;
public float interval;
void Start()
{
InvokeRepeating("RightFlash", 0, interval);
InvokeRepeating("LeftFlash", 0, interval);
}
void Update ()
{
if (ControlFreak2.CF2Input.GetAxis ("right") != 0) {
if (!IsInvoking("RightFlash"))
InvokeRepeating("RightFlash", 0.35f, 0.35f);
} 
else
{
CancelInvoke("RightFlash");
}
if (ControlFreak2.CF2Input.GetAxis ("left") != 0) {
if (!IsInvoking("LeftFlash"))
InvokeRepeating("LeftFlash", 0.35f, 0.35f);
} 
else
{
CancelInvoke("LeftFlash");
}
}
void RightFlash()
{
if(flash_right.activeSelf)
flash_right.SetActive(false);
else
flash_right.SetActive(true);
}
void LeftFlash()
{
if(flash_left.activeSelf)
flash_left.SetActive(false);
else
flash_left.SetActive(true);
}
}

一般来说,不要InvokeRepeating等与string一起使用!通过方法的名称调用方法不是很易于维护。如果您想使用它们,至少使用nameof以确保名称没有拼写错误。

那你就不能就这么做吗

void Update ()
{
if (ControlFreak2.CF2Input.GetAxis ("right") != 0) 
{
if (!IsInvoking(nameof(RightFlash)))
{
if(IsInvoking(nameof(LeftFlash)) CancelInvoke(nameof(LeftFlash));
InvokeRepeating(nameof(RightFlash), 0.35f, 0.35f);
}
} 
else
{
CancelInvoke(nameof(RightFlash));
}
if (ControlFreak2.CF2Input.GetAxis ("left") != 0) 
{
if (!IsInvoking(nameof(LeftFlash)))
{
if(IsInvoking(nameof(RightFlash)) CancelInvoke(nameof(RightFlash));
InvokeRepeating(nameof(LeftFlash), 0.35f, 0.35f);
}
} 
else
{
CancelInvoke(nameof(LeftFlash));
}
}
// Btw: These you can implement way shorter this way ;)
void RightFlash()
{
flash_right.SetActive(!flash_right.activeSelf);
}
void LeftFlash()
{
flash_left.SetActive(!flash_left.activeSelf);
}

在您的情况下,我实际上宁愿使用简单的计时器,因为无论如何您都需要Update方法来获取用户输入,所以为什么要过于复杂:

private float timerLeft;
private float timerRight;
void Update ()
{
if (ControlFreak2.CF2Input.GetAxis ("right") != 0) 
{
timerRight -= Time.deltaTime;
if (timerRight <= 0)
{
timerRight = interval;
RightFlash();
}
}
// simply make them exclusive so only one button is handled at a time
// if you press both at the same time right overrules
else if (ControlFreak2.CF2Input.GetAxis ("left") != 0) 
{
timerLeft -= Time.deltaTime;
if (timerLeft <= 0)
{
timerLeft = interval;
LeftFlash();
}
} 
}
void RightFlash()
{
flash_right.SetActive(!flash_right.activeSelf);
}
void LeftFlash()
{
flash_left.SetActive(!flash_left.activeSelf);
}

最新更新