简体   繁体   English

持续一段时间后重新启动级别Ontrigger

[英]Restart level Ontrigger after a duration

I would like to restart a level when a character enters a Trigger (which is the end of a race) after 5 or 10 seconds. 当角色在5或10秒后进入触发器(比赛结束)时,我想重新启动一个关卡。

I have a script that look like this : 我有一个看起来像这样的脚本:

public class WinBox : MonoBehaviour
{
    public Camera Camera1;
    private void OnTriggerEnter(Collider other)
    { 
        GameObject.Find("Camera (eye)").SendMessage("StopTimer");
    }
}

What should I add to make the level restart after the time that I want to define? 我要添加什么以使级别在要定义的时间后重新启动?

You can use coroutines to delay the call of the SceneManager . 您可以使用协程来延迟SceneManager的调用。 LoadScene function, along with the GetActiveScene function to get the information about the current scene : LoadScene函数以及GetActiveScene函数可获取有关当前场景的信息:

private IEnumerator RestartSceneAfterDelay( float delay = 10f )
{
    yield return new WaitForSeconds( delay );
    SceneManager.LoadScene( SceneManager.GetActiveScene().buildIndex ) ;
}

And call the function as follow : 并按如下所示调用函数:

private void OnTriggerEnter(Collider other)
{ 
    GameObject.Find("Camera (eye)").SendMessage("StopTimer");

    StartCoroutine( RestartSceneAfterDelay() ) ;
    // OR
    StartCoroutine( RestartSceneAfterDelay(5f) ) ;      
}

An other solution (but not as good as the first one) is to use the Invoke function to delay the call to the Scene manager. 另一种解决方案(但不如第一个解决方案好)是使用Invoke函数来延迟对场景管理器的调用。 Though, avoid this way because the call to the function is made from a string, which is hard to debug afterwards. 但是,请避免使用这种方式,因为对函数的调用是从字符串进行的,此后很难调试。

private void RestartScene()
{
    SceneManager.LoadScene( SceneManager.GetActiveScene().buildIndex ) ;
}

private void OnTriggerEnter(Collider other)
{ 
    GameObject.Find("Camera (eye)").SendMessage("StopTimer");

    Invoke( "RestartScene", 5f ) ;
}

To do something after a delay you could make an utility function like this: 要在延迟后执行一些操作,可以使实用程序功能如下:

static class Utils 
{
    public static IEnumerator DoAfterDelay(float delay, System.Action callback) 
    {
        yield return new WaitForSeconds(delay);
        callback();
    }
}

And then call it with StartCoroutine Like this 然后像这样用StartCoroutine调用它

private void RestartLevel() 
{
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}

private void OnTriggerEnter(Collider other)
{ 
    GameObject.Find("Camera (eye)").SendMessage("StopTimer");
    float secondsUntilRestart = 10;
    StartCoroutine(Utils.DoAfterDelay(secondsUntilRestart, RestartLevel));
}

From my experience, you often need this DoAfterDelay functionality, that's why I'd place it in a separate class instead of making it a local, private method 根据我的经验,您经常需要此DoAfterDelay功能,这就是为什么我将其放在单独的类中而不是将其设置为本地私有方法的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM