Axe*_*lle 0 c# timer unity-game-engine unity5
我正在尝试编写一个脚本,在1.5分钟后将所有灯关闭10秒,然后重新打开.
现在,似乎计时器被绕过了.我意识到这可能是因为时间永远不会是90左右.
话虽如此,我不知道如何得到我想要的结果.
我想过InvokeRepeating改用(如注释掉的那样),但那意味着灯光每次都会关闭更长时间.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LightsTimerTrigger : MonoBehaviour {
private GameObject[] allLights;
private float time = 0.0f;
private float secondTimer = 0.0f;
void Start () {
// Create array of lights
allLights = GameObject.FindGameObjectsWithTag("riddleLights");
//InvokeRepeating("lightsOn", 60.0f, 120.0f);
//InvokeRepeating("lightsOff", 60.10f, 120.10f); // Exponential
}
// Update is called once per frame
void Update () {
time += Time.deltaTime;
if(time%90 == 0)
{
secondTimer = time;
lightsOff();
Debug.Log("Lights off");
}
if (time == secondTimer + 10)
{
// Turn lights back on after 10 seconds
lightsOn();
Debug.Log("Lights back on");
}
}
void lightsOff()
{
foreach (GameObject i in allLights)
{
i.SetActive(false);
}
}
void lightsOn()
{
foreach (GameObject i in allLights)
{
i.SetActive(true);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)if(time%90 == 0)
这(几乎肯定)永远不会成真.
如果时间是90.000000001会怎么样?好吧,分开90部分,检查if(0.000000001 == 0)哪个是假的.
你应该这样纠正你的代码:
if(time >= 90) {
time -= 90;
//the rest of your code
}
Run Code Online (Sandbox Code Playgroud)
你需要为你的10秒延迟做类似的事情.
协程选项:
void Start () {
//existing code
StartCoroutine(FlickerLights());
}
IEnumerator FlickerLights() {
while(true) {
yield return new WaitForSeconds(90);
lightsOff();
Debug.Log("Lights off");
yield return new WaitForSeconds(10);
lightsOn();
Debug.Log("Lights back on");
}
}
Run Code Online (Sandbox Code Playgroud)