- Home /
Is there a way to reset prefabs to script variables in code?
So, what I am asking is: is there a code to reset the public members so that their variables are that of the attached script?
Ex. A script has a float that is set to 2 but I edit it in the editor of the prefab to 10. Now, is there a way I can reset this to 2 and all other variables to their respective initial value without explicitly setting them in code one by one?
I know you can do this by clicking the cogwheel in the script component and selecting reset, but I am looking for a way to do it in code.
Answer by Berenger · Mar 20, 2014 at 08:07 AM
You could remove the component with Destroy and then add it again. This should do :
public static void ResetComponents<T>(IEnumerable<GameObject> goCollection) where T : Component
{
foreach (GameObject go in goCollection)
{
if (go.GetComponent<T>() != null)
{
GameObject.DestroyImmediate(go.GetComponent<T>());
go.AddComponent<T>();
}
}
}
Your answer
Follow this Question
Related Questions
Trying to respawn prefabs after destroying them with a reset button 1 Answer
Invisable Projectile; Instantiate at Collisions 2 Answers
Place stars (prefabs) in random locations 3 Answers
Instantiating A Grass Prefab Multiple Times 1 Answer
How to shoot prefab, and then on colliding destroy a gameobject? 2 Answers