每秒激活和停用游戏对象

本文关键字:游戏 对象 激活 | 更新日期: 2023-09-27 18:33:04

我想做一个物体——龙头,它每 3 秒就会爆发 5 秒的火焰。但是我不知道该怎么做...我的脚本实际上看起来像这样:

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);
}
}

所以现在它的工作原理就像它开始燃烧,然后它循环激活和停用......所以它只是行不通。我还尝试了其他东西,如协程,调用重复,但没有成功。

每秒激活和停用游戏对象

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 启动协程,然后可以通过函数名称再次停止协程。您也可以先将OpenFire返回的IEnumerator保存到局部变量中,如果您不喜欢字符串类型,则可以对该变量使用 StopCoroutine

引用:http://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.htmlhttp://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html