Hello, I am relatively new to Unity, I was making a 2D project, and within that was making a Main Menu, it seems, that everytime I click play, it gives it a 5 second delay which is bizzare, and i dont know what causes this delay? does anyone know what the problem is, here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelManager : MonoBehaviour
{
[SerializeField] float LoadDelay = 0f;
public void LoadGame()
{
ReloadScene();
SceneManager.LoadScene(“Game”);
}
public void QuitGame()
{
Debug.Log(“Quitting”);
}
IEnumerator ReloadScene()
{
yield return new WaitForSecondsRealtime(LoadDelay);
FindObjectOfType().ResetScenePersist();
}
I’m not sure what your FindObjectOfType is trying to do, but keep in mind, nothing is happening right now like you think.
Your coroutine isn’t being called correctly and even if it was, it would get called, hit the yield, and then return to LoadGame to call the next line, which loads the game scene. The coroutine does not add a pause into the LoadGame call.
The FindObjectOfType, is getting a function from a script called “ScenePersists” In which destroys the scenes current avatars, before loading a new scene
Well, hate to break it to you, but that’s not what your code will do. If you want that call to happen before the scene load, you need the scene load call after it. Then, make sure you look up how to start a coroutine correctly so that it runs.
But also, looking at this, do you need a coroutine for this part? Are you thinking you need a delay?
Changing the scene will destroy stuff in the previous scene if you aren’t doing additive load. The coroutine itselff is not running with the code you posted.
Be careful above: changing that number will have no effect on scenes / prefabs. Here is why:
Serialized properties in Unity are initialized as a cascade of possible values, each subsequent value (if present) overwriting the previous value:
what the class constructor makes (either default(T) or else field initializers)
what is saved with the prefab
what is saved with the prefab override(s)/variant(s)
what is saved in the scene and not applied to the prefab
what is changed in Awake(), Start(), or even later etc.
Make sure you only initialize things at ONE of the above levels, or if necessary, at levels that you specifically understand in your use case. Otherwise errors will seem very mysterious.
Field initializers versus using Reset() function and Unity serialization: