- Home /
Object doesn't spawn after changing scene
So I wrote some code that's supposed to spawn a certain number of enemies after changing scene. I have verified that: - the list containing what to spawn stays the same - the spawner object does change scenes correctly - the different objects from which I get the list work correctly (as in they do provide the required information I ask of them) - I have the right "using" directories (system, unityEngine.SceneManagement, etc)
Here is the code:
public class Battle : MonoBehaviour {
public Vector3[] SpawnSpots;
public bool startBattle;
public int enemyAmount;
public string encounterType;
public GameObject[] Enemies;
void Awake()
{
DontDestroyOnLoad(gameObject);
}
void Update()
{
// detecting if Jesus started a battle
if (startBattle)
{
// detecting what kind of battle it is
if(encounterType == "demonic")
{
Enemies = gameObject.GetComponent<BattleList>().demonicEnemies;
}
else
{
Debug.Log("Wrong battle type");
}
// actually activating the battle mechanisms
SceneManager.LoadScene(1);
startBattle = false;
spawnEnemies();
}
}
void spawnEnemies()
{
// loop for spawning the enemies
for(int i = 0; i < enemyAmount; i++)
{
Instantiate(Enemies[0], SpawnSpots[i], Quaternion.identity);
}
}
}
Don't $$anonymous$$d the "Jesus" thing, my game is gonna be a bad "recreation" of the bible
Answer by highpockets · Aug 26, 2020 at 11:15 PM
Try LoadSceneAsync(): https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadSceneAsync.html
void Update()
{
// Press the space key to start coroutine
if (startBattle)
{
// Use a coroutine to load the Scene in the background
StartCoroutine(LoadYourAsyncScene());
}
}
//From the scripting API
IEnumerator LoadYourAsyncScene()
{
// The Application loads the Scene in the background as the current Scene runs.
// This is particularly good for creating loading screens.
// You could also load the Scene by using sceneBuildIndex. In this case Scene2 has
// a sceneBuildIndex of 1 as shown in Build Settings.
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(1);
// Wait until the asynchronous scene fully loads
while (!asyncLoad.isDone)
{
yield return null;
}
spawnEnemies();
}
I just added spawn enemy to the bottom of this coroutine and startBattle to the Update function, but everything else is right from the Scripting API
Holy damn it works. Thank you so much, I've been stuck with this problem for 3 days! Slow loading the scene seems to have been the answer (instead of suddenly doing it) as you nicely proved
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Bullets spawn behind the craft 3 Answers
A Simple Spawning System Code. 1 Answer
Stop a particle effect after spawn (or certain amount of time) 2 Answers