My persistent object spawner

The only problem I have with the persistent object spawner as shown in this tutorial is that it only spawns in the room(s) that you put the spawner in, and if you forget to add the spawner and go to test from that room, you’ll be missing all your persistent objects. So instead of using a MonoBehaviour as my spawner, I use a base C# class with the [RuntimeInitializeOnLoadMethod] attribute on the method that loads the objects. Since base classes can’t easily have a List where you add the objects in the editor, I instead put a PersistentObjects folder in my Resources folder, and all persistent objects go there.

public static class PersistentObjectSpawner
{
    [RuntimeInitializeOnLoadMethod]
    private static void InitializePersistentObjects()
    {
        var persistentObjects = Resources.LoadAll("PersistentObjects");
        foreach (GameObject persistentObject in persistentObjects) 
        {
            var obj = GameObject.Instantiate(persistentObject);
            GameObject.DontDestroyOnLoad(obj); 
        }

    }
}
3 Likes

Privacy & Terms