1.单例模式
untiy中单例模式有3种表达方式
第一种:(这种比较简单,但是需要新建一个空物体,并将脚本挂载上去。虽然简单,但是谨慎使用,此方法安全性不高)
public class GameObjectPool : MonoBehaviour
{
public static GameObjectPool _instance;
private void Awake()
{
_instance = this;
}
}
第二种:(这种方式不用挂载脚本,不过代码量较大)
public class GameObjectPool : MonoBehaviour
{
private GameObjectPool() { }
private static GameObjectPool _instance;
public static GameObjectPool GetInstance()
{
if (_instance == null)
{
//动态的生成一个名为“GameObjectPool”的对象并将单例脚本附加上去
_instance = new GameObject("GameObjectPool").AddComponent<GameObjectPool>();
}
return _instance;
}
}
第三种:(这种方式需要挂载脚本,而且代码量还较大)
public class GameObjectPool : MonoBehaviour
{
private GameObjectPool() { }
private static GameObjectPool _instance;
public static GameObjectPool GetInstance()
{
if (_instance == null)
{
_instance = new GameObjectPool ();
}
return _instance;
}
}