【问题标题】:yield waitforseconds() not working产量 waitforseconds() 不工作
【发布时间】:2013-04-23 02:18:23
【问题描述】:

我在播放器对象中有以下代码:

function Start () 
{
    GUI = GameObject.FindWithTag("GUI").GetComponent(InGameGUI);
}

function OnCollisionEnter(hitInfo : Collision)
{
    if(hitInfo.relativeVelocity.magnitude >= 2) //if we hit it too hard, explode!
    { 
        Explode();
    }
}

function Explode() //Drop in a random explosion effect, and destroy ship
{
    var randomNumber : int = Random.Range(0,shipExplosions.length);
    Instantiate(shipExplosions[randomNumber], transform.position, transform.rotation);
    Destroy(gameObject);

    GUI.Lose();
}

我的 GUI.Lose() 函数如下所示:

function Lose()
{
    print("before yield");
    yield WaitForSeconds(3);
    print("after yield");
    Time.timeScale = 0;
    guiMode = "Lose";
}

当调用explode 函数时,会调用松散函数并且我看到打印出消息“在yield 之前”。我等了三秒钟,但我从来没有看到“屈服后”消息。

如果我取出 yield,该函数将按预期工作,减去 3 秒的等待时间。

这是在 Unity 4 上的。这段代码直接来自我认为是在 Unity 3.5 上创建的教程。我假设代码在 Unity 3.5 中有效,因为网站上没有 cmets 询问为什么产量不起作用。

我做错了什么蠢事?

【问题讨论】:

    标签: unity3d yield unityscript


    【解决方案1】:

    你需要使用StartCoroutine,像这样:

    function Explode() //Drop in a random explosion effect, and destroy ship
    {
        var randomNumber : int = Random.Range(0,shipExplosions.length);
        Instantiate(shipExplosions[randomNumber], transform.position, transform.rotation);
        Destroy(gameObject);
    
        // Change here.
        yield StartCoroutine(GUI.Lose());
    
        // Or use w/out a 'yield' to return immediately.
        //StartCoroutine(GUI.Lose());
    }
    

    【讨论】:

    • 谢谢,这让我足够接近完成它。我将 yield StartCoroutine(GUI.Lose()) 放在 Destroy 之前。在此之前,我设置了 renderer.enabled = false;所以我的游戏对象会隐藏。 Lose() 函数完成,然后我的游戏对象被销毁。
    • 解释:因为使用yield语句可以随时暂停协程的执行。
    【解决方案2】:

    您也可以考虑在您的 Lose 函数上使用简单的 Invoke。

    function Start () 
    {
        GUI = GameObject.FindWithTag("GUI").GetComponent(InGameGUI);
    }
    
    function OnCollisionEnter(hitInfo : Collision)
    {
        if(hitInfo.relativeVelocity.magnitude >= 2) //if we hit it too hard, explode!
        { 
            Explode();
        }
    }
    
    function Explode() //Drop in a random explosion effect, and destroy ship
    {
        var randomNumber : int = Random.Range(0,shipExplosions.length);
        Instantiate(shipExplosions[randomNumber], transform.position, transform.rotation);
        Destroy(gameObject);
        Invoke("YouLose", 3.0f);
    }
    
    function YouLose()
    {
        GUI.Lose();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      • 2022-10-05
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      相关资源
      最近更新 更多