using UnityEngine;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.
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>();
DontDestroyOnLoad(g);
} else {
component = g.GetComponent<T>();
}
return component;
}
}
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:
Manager.Instance<MusicMixer>();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:
Post a Comment