After going to the menu scene and back to the game scene, an error occurs when calling Coroutine
I have a problem re-entering the game scene after the menu scene. On the first launch, everything works fine, but as soon as you go back to the scene with the menu, and back to the game one, an error appears: MissingReferenceException: The object of type 'GameControl' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object. UnityEngine.MonoBehaviour.StartCoroutine (System.Collections.IEnumerator routine) (at :0) GameControl.OnSceneLoaded (UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode) (at Assets/Scripts/GameControl.cs:79) UnityEngine.SceneManagement.SceneManager.Internal_SceneLoaded (UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode) (at :0)
I understand what the error is about, but have no idea why this error occurs, because the object has existed in the scene from the very beginning of the scene.
public class GameControl : MonoBehaviour
{
private static GameControl _gameControlInstance;
[SerializeField] private GameObject _playerForwardPref;
private GameObject _playerForward;
[SerializeField] private GameObject _playerGoalkeeperPref;
private GameObject _playerGoalkeeper;
private GameObject _targetPoint;
private GameObject _savePoint;
private Text _resulKick;
[SerializeField] private AudioClip _voicesFans;
private AudioSource _whistle;
private AudioSource _audioSource;
private Animator _animResultKick;
private bool _isKickForward = true;
private bool _endGame = false;
[SerializeField] private List<int> Player1 = new List<int>();
[SerializeField] private List<int> Player2 = new List<int>();
private void Awake()
{
Application.targetFrameRate = 60;
if (_gameControlInstance == null)
{
_gameControlInstance = this;
DontDestroyOnLoad(gameObject);
}
else if (_gameControlInstance != this)
{
Destroy(gameObject);
return;
}
}
void OnEnable()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
if (scene.name == "GameScene")
{
_playerForwardPref = Resources.Load("PlayerForward", typeof(GameObject)) as GameObject;
_playerGoalkeeperPref = Resources.Load("PlayerGoalKeeperBot", typeof(GameObject)) as GameObject;
_targetPoint = GameObject.FindGameObjectWithTag("TargetPoint");
_savePoint = GameObject.FindGameObjectWithTag("DirectionPoint");
_resulKick = GameObject.FindGameObjectWithTag("ResultKickText").GetComponent<Text>();
_animResultKick = _resulKick.GetComponent<Animator>();
_whistle = GameObject.FindGameObjectWithTag("whistle").GetComponent<AudioSource>();
if (!_isKickForward)
{
_targetPoint.SetActive(false);
}
else
{
_savePoint.SetActive(false);
}
SpawnPlayers();
StartCoroutine(StartGameDelay()); // An error occurs after re-entering the scene after the menu scene
}
}
private void Start()
{
_audioSource = gameObject.GetComponent<AudioSource>();
_audioSource.clip = _voicesFans;
_audioSource.Play();
}
private void Goal(int isGoal)
{
if (isGoal > -1)
{
GameResult();
_isKickForward = !_isKickForward;
}
if (isGoal == 1)
{
_resulKick.text = "GOOOAL!!!";
_animResultKick.SetBool("Show", true);
_playerForward.SendMessage("Goal", isGoal);
if (_isKickForward)
{
Player1.Add(1);
}
else
{
Player2.Add(1);
}
if (!_endGame)
{
StartCoroutine(Restart(3.0f));
}
}
if (isGoal == 2)
{
_resulKick.text = "MISS";
_animResultKick.SetBool("Show", true);
_playerForward.SendMessage("Goal", isGoal);
if (_isKickForward)
{
Player1.Add(0);
}
else
{
Player2.Add(0);
}
if (!_endGame)
{
StartCoroutine(Restart(3.0f));
}
}
if (isGoal == 3)
{
_resulKick.text = "GOALKEEPER SAVE!!!";
_animResultKick.SetBool("Show", true);
_playerForward.SendMessage("Goal", isGoal);
if (_isKickForward)
{
Player1.Add(0);
}
else
{
Player2.Add(0);
}
if (!_endGame)
{
StartCoroutine(Restart(3.0f));
}
}
}
private void GameResult()
{
int player1KickResults = 0;
int player2KickResults = 0;
foreach (int i in Player1)
{
if (i == 1)
{
player1KickResults += i;
}
}
foreach (int i in Player2)
{
if (i == 1)
{
player2KickResults += i;
}
}
if ((Player1.Count > 4) && (Player2.Count > 4))
{
if (player1KickResults > player2KickResults)
{
_endGame = true;
_resulKick.text = "YOU LOSE";
_animResultKick.SetBool("Show", true);
StartCoroutine(EndGame(5.0f));
}
}
if ((Player1.Count > 4) && (Player2.Count > 4))
{
if (player2KickResults > player1KickResults)
{
_endGame = true;
_resulKick.text = "YOU WIN!!!";
_animResultKick.SetBool("Show", true);
StartCoroutine(EndGame(5.0f));
}
}
}
private IEnumerator EndGame(float delay)
{
yield return new WaitForSeconds(delay);
SceneManager.MoveGameObjectToScene(gameObject, SceneManager.GetActiveScene());
SceneManager.LoadSceneAsync(1, LoadSceneMode.Single);
}
private IEnumerator Restart(float delay)
{
yield return new WaitForSeconds(delay);
SceneManager.LoadSceneAsync(2, LoadSceneMode.Single);
}
private void SpawnPlayers()
{
if (_isKickForward)
{
if ((_playerForwardPref != null) && (_playerGoalkeeperPref != null))
{
if ((_playerForward) || (_playerGoalkeeper))
{
Destroy(_playerForward.GetComponent<PlayerController>());
Destroy(_playerGoalkeeper.GetComponent<GoalKeeperBotControl>());
}
_playerForward = Instantiate(_playerForwardPref, new Vector3(-1.3f, 0, 36f), Quaternion.Euler(0, 25f, 0));
_playerForward.AddComponent<PlayerController>();
_playerGoalkeeper = Instantiate(_playerGoalkeeperPref, new Vector3(0, 0f, 41.0f), Quaternion.Euler(0, 180, 0));
_playerGoalkeeper.AddComponent<GoalKeeperBotControl>();
}
}
if (!_isKickForward)
{
if ((_playerForwardPref != null) && (_playerGoalkeeperPref != null))
{
if ((_playerForward) || (_playerGoalkeeper))
{
Destroy(_playerForward.GetComponent<ForwardBotControl>());
Destroy(_playerGoalkeeper.GetComponent<GoalKeeperPlayerControl>());
}
_playerForward = Instantiate(_playerForwardPref, new Vector3(-1.3f, 0, 36f), Quaternion.Euler(0, 25f, 0));
_playerForward.AddComponent<ForwardBotControl>();
_playerGoalkeeper = Instantiate(_playerGoalkeeperPref, new Vector3(0, 0f, 41.0f), Quaternion.Euler(0, 180, 0));
_playerGoalkeeper.AddComponent<GoalKeeperPlayerControl>();
}
}
}
private IEnumerator StartGameDelay()
{
yield return new WaitForSeconds(3.0f);
_whistle.Play();
_playerForward.SendMessage("StartGame", true);
}
}