這是我附加到按鈕的腳本,以便在單擊時加載下一個級別
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.SceneManagement;
public class LoadNextLevel : MonoBehaviour
{
static Action<string> LoadNextLvl;
void Start()
{
//The issue isn't with the delegate because i tried running the
//code without it
LoadNextLvl = (string name) => StartCoroutine("LoadFunc" , name);
}
IEnumerator LoadFunc(string name)
{
//This is to load the next level, it has nothing to do with the bug
int levelnum = int.Parse(name[5].ToString());
levelnum ;
SceneManager.LoadScene("Loading");
//i want to wait for a certain amount of time then load the next scene
yield return new WaitForSeconds(2f);
//For some reason the code stops here and doesn't continue even after
//I wait, in fact I tried yield return null but the same issue still
//occurs.
SceneManager.LoadScene("Level" levelnum);
}
public void Load()
{
//This function will be called using a button
LoadNextLvl(gameObject.scene.name);
}
}
正如我在評論中解釋的那樣,我嘗試了不同的方法,直到我將問題縮小到它在收益率回傳時停止的事實,即使我所做的與我找到的所有教程完全一樣。
uj5u.com熱心網友回復:
當你這樣做
SceneManager.LoadScene("Loading");
當前場景已卸載,并且該組件很可能與它一起被卸載,因此您的協程僅執行到第一個yield,然后永遠不會繼續。
而且你真的不需要那個代表。為什么不直接像這樣直接呼叫您的方法:
public class LoadNextLevel : MonoBehaviour
{
private IEnumerator LoadFunc()
{
var levelnum = int.Parse(gameObject.scene.name[5].ToString());
levelnum ;
// Make sure this is not destroyed when the scene is unloaded
DontDestroyOnLoad (gameObject);
SceneManager.LoadScene("Loading");
yield return new WaitForSeconds(2f);
SceneManager.LoadScene("Level" levelnum);
// Then once you don't need this anymore now destroy it
Destroy (gameObject);
}
public void Load()
{
StartCoroutine(LoadFunc());
}
}
除了使用字串,您還可以使用
var nextIndex = SceneManager.GetActiveScene().buildIndex 1;
然后稍后
SceneManager.LoadScene(nextIndex);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/419087.html
標籤:
上一篇:如何使型別別安全
