Variables of prefabs

Hi. I have 20 prefab objects defined to the spawner object and all of them have the isSpawned value false and their levels are between 1-7. My main question is that when I spawn all the objects, the isSpawned value of all of them becomes true and they remain that way even if I stop and start again the project. Shouldn’t it be reset or is there something I missed?
Spawner script:

using UnityEngine; 

public class Spawner : MonoBehaviour
{
    public Daytime daytime; //Take day
    public GameObject[] prefabs; // Prefabs

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            SpawnObject();
        }
    }

    void SpawnObject()
    {
        // Prefab list
        List<GameObject> availablePrefabs = new List<GameObject>();

        // add prefabs to list
        foreach (var prefab in prefabs)
        {
            ObjectProperties properties = prefab.GetComponent<ObjectProperties>();

            if (!properties.isSpawned && daytime.Day >= properties.Level)
            {
                availablePrefabs.Add(prefab); // add available ones
            }
        }

        // random pick
        if (availablePrefabs.Count > 0)
        {
            int randomIndex = Random.Range(0, availablePrefabs.Count); // random index
            GameObject selectedPrefab = availablePrefabs[randomIndex]; // random prefab

            ObjectProperties selectedProperties = selectedPrefab.GetComponent<ObjectProperties>();
            selectedProperties.isSpawned = true;
            Debug.Log("Spawned: " + selectedPrefab.name + ", Level: " + selectedProperties.Level + ", Day: " + daytime.Day);
        }
        else
        {
            Debug.Log("No valid prefab to spawn.");
        }
    }

} 

Because you’re modifying the value of the prefab asset itself, which causes the changes to persist between play mode sessions.

You need to only be modifying instances in the scene at runtime.

1 Like

Well, does this mean that it is a small save system in its own right? Actually, I wanted to do this job by preparing a savesystem script.
I mean can I use this as a save system?

No it cannot. Your assets cannot be mutated in a build, you will only be modifying the in-memory instance generated from the asset. Everything will return as it were when you next open the game.

You will still need to devise a proper system of writing data to disk.

1 Like

Okay, thank you for your quick response

1 Like