Friday, October 29, 2010

Generic Manager Component

We've found ourselves using this pattern across a number of projects.
using UnityEngine;
using System.Collections;
public class Manager : MonoBehaviour {
static public T Instance<T>() where T : Component {
T component;
var g = GameObject.Find("/" + typeof(T).ToString());
if(g == null) {
g = new GameObject(typeof(T).ToString());
component = g.AddComponent<T>();
} else {
component = g.GetComponent<T>();
return component;
It is used to create components which persist across level loads, without needing to create GameObjects to hold those components in the editor. It solves the problem where you may need to load levels in a specific order to make sure your persistent game objects are available in the level you wish to test.

Eg, you may have a MusicMixer component which will continue to play music across Application.LoadLevel calls. Instead of creating the MusicMixer in every scene, (or in one scene and marking it with DontDestryOnLoad) you can access it via:
And if it does not exist in the level already, it will be created and returned, and also used across subsequent references to the MusicMixer.

No comments:

Popular Posts