- Home /
Reseting Component/GameObject to its initial scene state.
I would like to create a basic behaviour for my components that lets them be reset to the original values at the begining of the scene when they are complete. In otherwords, I want a simple way to create 'Repeat on Complete' functionality. Without reloading the scene or instantiating a prefab, is there a way to reset an object/component to its original scene state?
Answer by duck · Apr 07, 2010 at 02:12 PM
I don't think there's a built-in way, but you could implement this yourself by storing the values that you'd like to be re-set in the Start function. Eg:
var originalPosition : Vector3; var originalRotation : Quaternion;
function Start() { originalPosition = transform.position; originalRotation = transform.rotation; }
function Reset() { transform.position = originalPosition; transform.rotation = originalRotation; if (rigidbody != null) { rigidbody.velocity = Vector3.zero; rigidbody.angularVelocity = Vector3.zero; } }
If you wanted to re-set other values such as animation state, visibility, etc, you'd have to add each of these as separate variables, with the corresponding lines of code to reset them.
Answer by lassade · Aug 13, 2013 at 07:52 PM
Make your object an prefab and try
UnityEditor.PrefabUtility.ResetToPrefabState(this.gameObject)
It not seems to work for me though, but the docs says "Resets the properties of the component or game object to the parent prefab state"
Answer by sathya _m · Nov 04, 2013 at 07:40 AM
//read all game objects and set initial position when ever it needs
in c#
private Dictionary<GameObject,Vector3> current_obj_trans_value = new Dictionary<GameObject,Vector3>();
public void intial_pos_set()
{
object[] allObjects = FindObjectsOfTypeAll(typeof(GameObject)) ;
foreach(object thisObject in allObjects)
{
if (((GameObject) thisObject).activeInHierarchy &&((GameObject)
thisObject).GetComponent() != null)
current_obj_trans_value[((GameObject)thisObject)]=
((GameObject)thisObject).transform.position;
}
}
public void reset_tranform_pos() {
foreach(KeyValuePair<GameObject,Vector3> allactobj in
current_obj_trans_value)
{
allactobj.Key.transform.position= allactobj.Value;
}
}
Answer by MihaMarn · Jun 16, 2021 at 01:53 PM
Create an object prefab with desired properties. In-game instantiate this prefab. Change those properties however you like. When you need to set defaults, simply destroy this game object and instantiate a new one from the prefab. Now, this new one will have all props set to default. If you want to change some of those, simply adjust them just before instantiation.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
'enabled' is not a member of UnityEngine.Component 2 Answers
Problem with click to display information 1 Answer
Scene object scripting 1 Answer
Save game objects to new scene 0 Answers