Enhancements to PersistentObjectSpawner

I added the ability to have a list of objects to spawn along with the ability to have a custom name for them when they spawn. If no custom name was entered, it will use the name from the prefab

  public class PersistentObjectSpawner : MonoBehaviour
    {
        [Tooltip("These prefabs will only be spawned once and be persisted between scenes")]
        [ SerializeField] 
        private List <PersistentObject> persistentObjectPrefabs;

        private bool _hasSpawned;
        private void Awake()
        {
            if (_hasSpawned) return;
            SpawnPersistentObjects();
            _hasSpawned = true;
        }

        private void SpawnPersistentObjects()
        {
            foreach (var persistentObjectPrefab in persistentObjectPrefabs)
            {
                GameObject persistentObject = Instantiate(persistentObjectPrefab.prefab);
                persistentObject.name = persistentObjectPrefab.nameOfObject == null ? persistentObjectPrefab.prefab.name : persistentObjectPrefab.nameOfObject;
                DontDestroyOnLoad(persistentObject);
            }
        }
        
    }

    [System.Serializable]
    public class PersistentObject
    {
        public string nameOfObject;
        public GameObject prefab;
    }
3 Likes

Looks good! Great job :clap:

That can be handy, especially since that name will be easily reflected in the hierarchy of the DontDestroyOnLoad scene that is attached to the game.

Privacy & Terms