Posts Tagged ‘ResetBehaviour’

The Way Things Used To Be :: Reset Components and Unity 3D

One of the very interesting aspects of Unity 3D and its architecture is the fact that it is component based. This one factor makes it very easy to implement some very interesting behavior in your games that separates concerns rather nicely. One such interesting notion is that of a Reset component.

When the Horseman created Hug Monster he realized quickly that he’d need to store the initial positions of the game’s objects somehow. Re-loading the Scene every time the player dies is simply unacceptable given the time Unity takes to perform loads, so somehow there must be a way to easily store initialization data. In other langauges such as AS3 the most tempting way to do this would be to implement something like :

  public function getInitialValuesFromScene():void{ /*collect initial values*/ }
  public function reset():void{ /*reset to initial values*/ }

As a consequence, all game objects would carry this baggage around, and they all must remember to subclass HugMonsterGameObject whether they needed the functionality or not. This doesn’t sound bad on its face, but it can bloat the number of responsibilities of a given class, such that it simply has to concern itself with “too much.” On the bright side, Unity’s component-based architecture allows us to split this behavior out completely! I do have a Player class, and a Hugmonster class, but neither of them knows a thing about how to grab initial coordinates or restore to an “initial” state. Instead, the gameObjects that have Player and Hugmonster components (as well as everything that can be moved or altered) have a ResetBehaviour object sitting alongside their “main” component.

How it works is as such.

// In the file ResetBehaviour.cs
//    This is merely an abstract class, to give 
//    us a typed Component that is responsible 
//    for Resetting things.
using UnityEngine;
using System.Collections;
public class ResetBehaviour : MonoBehaviour {	
	virtual public void RecordStartingVariables(){}	
	virtual public void ResetGO(){}
// In the file GenericResetBehaviour.cs
//    Our most basic implementation of ResetBehaviour.
//    This is ideal for things like the blocks that 
//    the Hug Monster can shove around, or for
//    other miscelaneous objects that only move 
//    with position / rotation and have a 
//    changing velocity.
using UnityEngine;
using System.Collections;
public class GenericResetBehaviour : ResetBehaviour {
	public Vector3 resetToPosition;
	public Quaternion resetToRotation;
	public Vector3 resetRigidBodyToVelocity;
	public Vector3 resetAngularVelocity;
	// Use this for initialization
	void Start () {
                // Unity's default Start method
                // is an ideal spot to initialize
                // since this is where the object
                // was placed in the editor.
	override public void RecordStartingVariables(){
		resetToPosition = transform.position;
		resetToRotation = transform.rotation;
		if(rigidbody != null){
			resetRigidBodyToVelocity = rigidbody.velocity;
			resetAngularVelocity = rigidbody.angularVelocity;
	override public void ResetGO(){
		Debug.Log("Default ResetBehavoiur");
		transform.position = resetToPosition;
		transform.rotation = resetToRotation;
			rigidbody.velocity = resetRigidBodyToVelocity;
			rigidbody.angularVelocity = resetAngularVelocity;

If an object needs a more specialized form of ResetBehaviour, I can simply derive from GenericResetBehaviour without necessarily overriding anything in the Player, Hugmonster, Switch, Wall, Camera, or any other class definition. This makes content creation and behavioral scripting ridiculously flexible.

But Mr. Horseman, why make Reset components for all these objects? Don’t you have to then grab that component from each game object, by specific type, and call ResetGO() on it?

Aaaah, I’m glad you asked. You do NOT have to do any such thing! The reset level code, which lives inside the GameManager class looks something like this…

public void RestartLevel(){
		ResetBehaviour[] rbs = Component.FindObjectsOfType(typeof(ResetBehaviour)) as ResetBehaviour[];
		foreach(ResetBehaviour rb in rbs){
                // a few more lines of code for displaying the Game Over text go here.

Because the ResetBehaviour class is virtual, and because all the Reset components derive from it in some manner, all I have to do is find every component derived from ResetBehaviour using the handy function shown above and then iterate through the resulting array an call ResetGO() on each. Every item in the scene will reset to its initial position as specified by the component without any further work on the developer’s part.

I have to say that I first looked at the component system and saw the potential for chaos, but in fact the philosophy underpinning the Unity Editor gives you ways to funnel that chaos into pure elegance.

Tags: , , , ,