I’ve been trying to integrate the persistent object spawner code that’s in one of the RPG courses which makes sure that the objects remain in between scenes and I’ve bumped into a bit of a weird bug that I don’t understand and am hoping that someone has seen something like this before.
The code works and creates the persistent object as expected on the first play in Editor mode.
However, once I hit play again (after stopping it). The persistent object does not load.
According to the logs, the persistent object has spawned. However after adding checks it appears to be blank/ missing + does not contain the GetInstanceID()
attribute.
I then added the condition that if the persistent object is null then SpawnPersistentObject again.
if(hasSpawned && persistentObject == null)
{
Debug.Log("Persistent object thinks it's been created but it's missing");
SpawnPersistentObjects();
}
This resulted in TWO persistent objects being in the scene. The number of objects appears to cap at two (stop/ start afterwards does not add more objects). The name of the objects are also exactly the same (i.e. no “(1)” being tagged on).
The logs indicate that these are two DIFFERENT objects.
However, to enter that spawn loop the SECOND play-through, it needed to pass the null check (persistent object is null). This implies that the second persistent object only instantiates AFTER the game begins (and so hasn’t really persisted)
Any idea what’s happening here?
A GUESS may be that it’s something about a race condition (?) as the “Dialogue System” (other package) also creates a dontdestroyonload
object. Though I would have thought that multiple persisted objects would be fine + it works the first time around + works with duplication if I add the additional check.
Code below
public class PersistentObjectSpawner : MonoBehaviour
{
// CONFIG DATA
[Tooltip("This prefab will only be spawned once and persisted between " +
"scenes.")]
[SerializeField] GameObject persistentObjectPrefab = null;
// PRIVATE STATE
static bool hasSpawned = false;
GameObject persistentObject = null;
// PRIVATE
private void Awake() {
if(hasSpawned && persistentObject == null)
{
Debug.Log("Persistent object thinks it's been created but it's missing");
SpawnPersistentObjects();
}
else if (hasSpawned)
{
Debug.Log("Persistent object has already been created");
Debug.Log("Persistent object: " + persistentObject);
Debug.Log("Is Persistent object null: ");
Debug.Log(persistentObject == null);
Debug.Log("Persistent object ID: " + persistentObject.GetInstanceID());
return;
}
SpawnPersistentObjects();
hasSpawned = true;
}
private void SpawnPersistentObjects()
{
Debug.Log("Spawning persistent object");
persistentObject = Instantiate(persistentObjectPrefab);
Debug.Log("Persistent object ID: " + persistentObject.GetInstanceID());
DontDestroyOnLoad(persistentObject);
}
}