WaitForSeconds on C#

孤街醉人 提交于 2021-01-28 01:43:31

问题


Look at this simple code:

function Start()
{
    yield WaitForSeconds (4);
    Application.LoadLevel(1);
}

It works! I'm trying to make something similiar using C#, but the processor just ignore the WaitForSeconds. This is my code in C#:

using UnityEngine;
using System.Collections;

public class openingC : MonoBehaviour
{
    void Start()
    {
        executeWait(5);
        Application.LoadLevel(1);
    }

    void executeWait(float aux)
    {
        StartCoroutine(Wait(aux));
    }

    IEnumerator Wait(float seconds)
    {
        yield return new WaitForSeconds(seconds);
    }
}

Can someone explain to me why it's not working? Thanks for your time.


回答1:


public class openingC : MonoBehaviour
{
    void Start()
    {
        executeWait(5);
        Application.LoadLevel(1);
    }

    void executeWait(float aux)
    {
        StartCoroutine(Wait(aux));
    }

    IEnumerator Wait(float seconds)
    {
        yield return new WaitForSeconds(seconds);
    }
}

First, the Start method runs, executeWait is called, the program jumps to the method. It finds the coroutine and starts running it until a yield is found or the end of the method. Yield returns to the program, the pointer goes back up to executeWait and finishes the method. The pointer goes back up to Start and calls for Application.LoadLevel.

You want to hang the LoadLevel call.

public class openingC : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(Wait(5));
    }

    //You don't need executeWait

    IEnumerator Wait(float seconds)
    {
        yield return new WaitForSeconds(seconds);
        Application.LoadLevel(1);
    }
}



回答2:


Try this:

Thread.Sleep(500); //500 millisecond waiting...

Reference




回答3:


This should also be okay.

    IEnumerator Start()
    {
        yield return new WaitForSeconds(4);
        Application.LoadLevel (1); 
    }


来源:https://stackoverflow.com/questions/34242353/waitforseconds-on-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!