- Home /
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?
Answer by plamusse42 · Nov 07, 2020 at 04:33 PM
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.
Thanks for the suggestion. This will definitely work, but it seems kinda taxing to switch around prefabs all the time. Especially if the program gets bigger in scale and a lot more prefabs needs to be switched and tracked.
Answer by CodesCove · Nov 07, 2020 at 07:38 PM
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: https://unity.com/how-to/architect-game-code-scriptable-objects
Will definitely tinker around with Scriptable Objects next time. In the meantime, I fixed my issue with a simple save and load class. But then again, this feels kinda overkill for what I really needed. Also, it wastes disk space... $$anonymous$$aybe it's time to get into ScriptableObjects ~ Thanks for the point in the right direction.
Your answer
![](https://koobas.hobune.stream/wayback/20220613015340im_/https://answers.unity.com/themes/thub/images/avi.jpg)