Hi there,
Something is bugged in my code.
When transitioning from Level 2 to Level 3 all Enemy and Coin Placements in Level 3 are the ones of Level 1. When I start level 3 directly the placements are correct. How come the game loads the ScenePersist Object from lvl 1 in lvl 3 when transitioning from lvl 2 to lvl 3?
ScenePersist.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScenePersist : MonoBehaviour
{
void Awake()
{
int numScenePersists = FindObjectsOfType<ScenePersist>().Length;
if (numScenePersists > 1)
{
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
public void ResetScenePersist()
{
Destroy(gameObject);
}
}
GameSession.cs
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameSession : MonoBehaviour
{
[SerializeField] int playerLives = 3;
[SerializeField] TextMeshProUGUI livesText;
[SerializeField] TextMeshProUGUI scoreText;
[SerializeField] int playerScore = 0;
void Awake()
{
int numGameSessions = FindObjectsOfType<GameSession>().Length;
if (numGameSessions > 1 )
{
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
void Start()
{
livesText.text = playerLives.ToString();
scoreText.text = playerScore.ToString();
}
public void ProcessPlayerDeath()
{
if (playerLives > 1)
{
TakeLife();
}
else
{
ResetGameSession();
}
}
public void AddToScore(int pointsToAdd)
{
playerScore += pointsToAdd;
scoreText.text = playerScore.ToString();
}
void TakeLife()
{
playerLives--;
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(currentSceneIndex);
livesText.text = playerLives.ToString();
}
void ResetGameSession()
{
FindObjectOfType<ScenePersist>().ResetScenePersist();
SceneManager.LoadScene(0);
Destroy(gameObject);
}
}
LevelExit.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelExit : MonoBehaviour
{
[SerializeField] float levelLoadDelay = 1f;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
StartCoroutine(LoadNextLevel());
}
}
IEnumerator LoadNextLevel()
{
yield return new WaitForSecondsRealtime(levelLoadDelay);
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
int nextSceneIndex = currentSceneIndex + 1;
if(nextSceneIndex > SceneManager.sceneCount)
{
nextSceneIndex = 0;
}
FindObjectOfType<ScenePersist>().ResetScenePersist();
SceneManager.LoadScene(nextSceneIndex);
}
}
When transitioning from lvl2 to lvl3
When starting lvl3 directly
ScenePersist of lvl1