So I am quite new to Unity (working on first project), and I was following along with a Jason Weimann tutorial, eventually I finished and now have 3 levels. It works as a mimic of angry birds, and it is coded so that as soon as all the monsters are destroyed, the next level is loaded. However, I wanted to adjust it so that there was a small delay, for the satisfaction of completing the level, etc., but I could not figure out how to do this. I was researching and found something about coroutines, but I’m not exactly sure how they work, I am using visual studio, and sorry in advance for the messy coding and formatting haha
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelController : MonoBehaviour
{
private bool _birdLaunched;
private float _timeSittingAround;
private bool _birdTooLong;
private static int _nextLevelIndex = 1;
private monster[] _enemies;
private void OnEnable()
{
_enemies = FindObjectsOfType<monster>();
}
// Update is called once per frame
void Update()
{
foreach (monster monster in _enemies)
{
if (monster != null)
return;
}
Debug.Log("You killed all enemies");
int v = _nextLevelIndex++;
string nextLevelName = "Level" + _nextLevelIndex;
SceneManager.LoadScene(nextLevelName);
}
}
The following code is a very basic solution.
Define a float variable that will count the time since all enemies have been killed (levelLoadUpdate). If all enemies have been killed add Time.deltaTime to it. If the variable is below a threshold return, else load the level.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelController : MonoBehaviour
{
private bool _birdLaunched;
private float _timeSittingAround;
private bool _birdTooLong;
private static int _nextLevelIndex = 1;
private monster[] _enemies;
private void OnEnable()
{
_enemies = FindObjectsOfType<monster>();
}
float levelLoadUpdate;
// Update is called once per frame
void Update()
{
foreach (monster monster in _enemies)
{
if (monster != null)
return;
}
levelLoadUpdate += Time.deltaTime;
if(levelLoadUpdate < 2f)
return;
Debug.Log("You killed all enemies");
int v = _nextLevelIndex++;
string nextLevelName = "Level" + _nextLevelIndex;
SceneManager.LoadScene(nextLevelName);
}
}
For brackeys, what he did was create a function with SceneManager.LoadScene(“nextLevelName”, or SceneManager.GetActiveScene().buildIndex +1 or something)
public void NextLevel()
{
SceneManager.LoadScene("nextLevelName")
}
Basically take that method, stuff it into a function. Then, whenever you want to go to the next scene, use Invoke("NextLevel", 5f); unity will wait 5 seconds before calling NextLevel(), which gives 5 seconds time for the player before the next scene.
tldr use a function to call the next scene, use Invoke(“Functionname”, delayinfloat); to create a delay.