我想制作一个物体 - 龙头,它会在5秒内每3秒爆发一次火焰。但我不知道该怎么做...我的脚本实际上是这样的:
using UnityEngine;
using System.Collections;
public class Dragon_Head_statue: MonoBehaviour {
public GameObject openFire;
private bool IsActive;
void Update()
{
Invoke("OpenFire", 4);
}
void OpenFire()
{
IsActive = !IsActive;
openFire.SetActive(IsActive);
}
}
所以现在它起作用就像它开始燃烧然后它循环激活和停用......所以它只是不起作用。我还尝试过coroutines等其他东西,InvokeRepeating没有成功。
答案 0 :(得分:0)
与new WaitForSeconds(3.0f)
结合使用的协程是解决此问题的完美解决方案。看看这段代码:
using UnityEngine;
using System.Collections;
public class Dragon_Head_statue: MonoBehaviour {
public GameObject openFire;
public bool IsActive = false; //IsActive means here that we're in a loop bursting flames, not that we're currently not bursting flames.
void Start()
{
//Start the coroutine
//5 seconds flame burst, then wait 3 secs
StartCoroutine(OpenFire(5.0f, 3.0f));
}
/* function for making this thing stop */
void StopFlames()
{
//Stop the first running coroutine with the function name "OpenFire".
StopCoroutine("OpenFire");
IsActive = false; //propage this metadata outside
//Additionally turn of the flames here if we were just
//in the middle of bursting some
openFire.SetActive(false);
}
IEnumerator OpenFire(float fireTime, float waitTime )
{
IsActive = true; //For outside checking if this is spitting fire
while(true)
{
//Activate the flames
openFire.SetActive(true);
//Wait *fireTime* seconds
yield return new WaitForSeconds(fireTime);
//Deactivate the flames
openFire.SetActive(false);
//Now wait the specified time
yield return new WaitForSeconds(waitTime);
//After this, go back to the beginning of the loop
}
}
}
您使用StartCoroutine
启动协程,然后您可以再次通过函数名称停止协程。您还可以先将IEnumerator
返回的OpenFire
保存到本地变量中,如果您不喜欢该字符串输入,请对该变量使用StopCoroutine
。
参考文献: http://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html http://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html