- Home /
How do I reset a script's values at run time to what they were at start?
I've looked all over but I haven't found an answer. Say I have an array called MyPrefabs:
public GameObject[] MyPrefabs;
I add the prefabs I want to the array in the inspector. Let's say I have a Cube object with a CubeScript attached. CubeScript has a speed variable which's default is 5.
public class CubeScript
{
public int Speed = 5;
}
I save the Cube with the CubeScript attached to a prefab and assign the prefab to the MyPrefabs Array.
I then decide that I want to modify that value.
MyPrefabs[0].GetComponent<CubeScript>().Speed = 10;
So now let's say I want the default value again. How would I go about doing that? Obviously I could store the Speed variable in a separate variable, but that wouldn't really be feasible when I have multiple Prefabs each having multiple variables. I thought about copying the MyPrefabs array at Start to an Array called, say, MyPrefabsDefault then assigning MyPrefabs to the MyPrefabsDefault when I wanted to reset it to it's original values, but I'm not sure how that would work or if it's the best way.
Answer by clunk47 · Nov 26, 2013 at 06:36 PM
// Inspector variables
public float speed = 5;
public float defSpeed;
public void Start()
{
defSpeed = speed;
}
public void ChangeSpeed()
{
// change the speed variable somehow...
}
public void ResetSpeed()
{
speed = defSpeed;
}
Answer by Jamora · Dec 04, 2013 at 08:24 AM
Instead of having duplicate variables; one for the actual value and one for the default, just use the Reset function. Set the default values manually inside. Reset is called when the reset-button (appears when right clicking on the Component name) is pressed or when the component is added for the first time. It is just a normal function, so nothing stops you from calling it yourself when you need to reset your values.
public int speed;
void Reset(){
speed = 5;
}
You forgot one aspect: The speed may not be initialized with 5 in the inspector, but maybe with say 7. Now, he wants to reset this value he needs some sort of backup variable that stored this "inspector set value".
Answer by haim96 · Nov 26, 2013 at 12:00 PM
in your cubescript you could add another int for old speed so each prefab will save the old value for it self. i don't think there is away to avoid saving values for later use other then store them in variables.
Thanks for the answer. I don't think that making a duplicate variable for each single variable in every single class would be reasonable though. I hope there's another way.
You can just assign default values in start() and call start() again when you want to reset to those values.