- Home /
Reset an GO to its original state (start app state)
So I have a UI prefab with a lot of children and in the runtime, I do a lot of modifications to that GO. Is there a way to simply bring the whole state of that GO to its initial state in real-time? (basically to undo everything)
Answer by evskii · Nov 11, 2021 at 02:42 PM
There are a bunch of complicated ways of doing it where you track all of the changes that have been made and revert them one by one, but if the GO is relatively independent (i.e not having too many external references/dependencies) you can just spawn a new version of the prefab, and delete the one that has all of the changes.
Answer by UnityPlum · Nov 11, 2021 at 08:38 PM
Sure you could! One way to do that is have two scripts. For the example we will use Foo and Bar. So you want to attach "Foo" to a single gameObject and it will be a manager of sorts. You will attach Bar to all of the gameObjects you want to be reset. The Foo script will look like this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Foo : MonoBehaviour
{
public Dictionary<GameObject, Vector3> startingPositions = new Dictionary<GameObject, Vector3>();
public static Foo instance;
private void Awake() {
instance = this;
}
public void ResetAll()
{
foreach(KeyValuePair<GameObject, Vector3> entry in startingPositions) {
entry.Key.transform.position = entry.Value;
}
}
}
And Bar:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bar : MonoBehaviour
{
void Start()
{
Foo.instance.startingPositions.Add(gameObject, transform.position);
}
}
And whenever you want to reset all gameObjects simply wherever in any script you like go Foo.instance.ResetAll();
I just tested it and it worked! You can do the same thing for rotations, just replace the Vector3
's with Quaternion
Your answer
Follow this Question
Related Questions
How could I save my Gameobject inside a defined Prefab ? 1 Answer
Change GameObject According to UI selection 2 Answers
SetActive modifies Prefab 1 Answer
transforming a prefab randomly at runtime 3 Answers
Instantiate object 1 Answer