Make changes in prefabs persistent.

Lets say I have a prefab. I can instantiate it with the press of a button. I can do stuff to it, for example change a bool. Now, when it’s destroyed and I want to instantiate it again (during the same session), it gets instantiated with its original values. How can I make changes persistent within a session?

Hey @Helldubs !

I don’t know what is the best practice but I came up with this :

You can use an other prefab as a prefab manager.

public class PrefabManager : MonoBehaviour
{
    public Color color;
    public GameObject square;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            Instantiate(square, transform);
        }
    }
}

AND

public class Square : MonoBehaviour
{
    public GameObject manager;
    // Start is called before the first frame update
    void Start()
    {
        Color managerColor = manager.GetComponent<PrefabManager>().color;
        GetComponent<SpriteRenderer>().color = new Color(managerColor.r,
            managerColor.g, managerColor.b);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

The trick is to drag the prefab from your project window in the GameObject public variable in both the PrefabManager and in the Square prefab (BTW this one could be anything else).

So to summarize : 2 Prefabs with 2 differents Scripts and give each the other prefab.

I suggest you to use ScriptableObject to store the data.
You can reference the prefabs from there and build & attach component that registers the GameObject reference to the scriptable object in the Start. That way you can have persistent data in the asset file even if you destroy the referenced gameobject and instantiate it again…

There is some learning to do how the SO works and how to best utilize it. I have mostly positive experience with this and it solves and makes a lots of data persistence (also save / load) + object reference stuff easier.

Check this out first: Architect your code for efficient changes and debugging with ScriptableObjects | Unity