C# 每秒激活和停用游戏对象

C# 每秒激活和停用游戏对象,c#,android,unity5,C#,Android,Unity5,我想做一个物体——龙头,它会燃烧5秒,每3秒燃烧一次。但我不知道该怎么做。。。我的脚本实际上如下所示: using UnityEngine; using System.Collections; public class Dragon_Head_statue: MonoBehaviour { public GameObject openFire; private bool IsActive; void Update() { Invoke("OpenFire", 4); } voi

我想做一个物体——龙头,它会燃烧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);
}

}

所以现在它的工作原理就像它开始燃烧,然后循环激活和停用。。。所以它就是不起作用。我还尝试了其他方法,比如协同路由,调用重复,但没有成功。

协同路由与
新的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
        }
    }

}
您可以使用
startcroutine
启动协同程序,然后可以根据函数名再次停止协同程序。您还可以首先将OpenFire返回的
IEnumerator
保存到一个局部变量中,如果您不喜欢字符串类型,可以对该变量使用
StopCorroutine

参考资料:

如此清晰易懂。我现在(终于)明白了。谢谢你。这很可能是另一个主题,甚至不是一个剧本,但我正在考虑如何平滑它。我的意思是,当火焰被激活时,它们就消失了。。。什么看起来很奇怪。他们应该有个结局,就像。。。嗯,我不知道怎样才能把它做好。。你知道,当你产生一股火焰时,每个粒子都会飞走。所以它应该停下来把它们推出去,但被创造出来的应该会继续发抖。你知道我的意思吗?听起来火焰喷射器应该通过让他为每个火球创建一个
GameObject
,给它们一个启动速度,并在一段时间后摧毁它们来实现。这样,当游戏对象/脚本被停用时,它只会停止创建更多的火球。它当前是粒子系统还是发射器?然后可以更改发射器的
.emit
字段,使其停止发射更多粒子,请参见或。否则会有一个新问题。我也这么想。。。使其成为火球发射器而不是火焰编织器。是的,我目前只使用粒子系统。我以前没听说过发射器。。。我将查看这些链接。