一、基本写法
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
private static NewBehaviourScript instance;
public static NewBehaviourScript GetInstance()
{
return instance;
}
private void Awake()
{
instance = this;//脚本挂载在游戏对象上,运行时赋值
}
}
二、改进后
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingletonMono<T> : MonoBehaviour where T:MonoBehaviour
{
// Start is called before the first frame update
private static T instance;
public static T GetInstance()
{
return instance;
}
protected virtual void Awake()
{
instance = this as T;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : SingletonMono<NewBehaviourScript>
{
private void Start()
{
NewBehaviourScript.GetInstance();
}
protected override void Awake()
{
base.Awake();
}
}
继承了MonoBehaviour的单例模式对象,需要我们自己保证它的唯一性,不要重复挂载一个脚本,否则它的唯一性就会被破坏。
三、自动创建对象并挂载脚本的方法,不用手动挂载脚本,防止重复挂载
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingletonAutoMono<T> : MonoBehaviour where T : MonoBehaviour
{
// Start is called before the first frame update
private static T instance;
public static T GetInstance()
{
if (instance == null)
{
GameObject obj = new GameObject();
//设置对象的名字为脚本名
obj.name = typeof(T).ToString();
GameObject.DontDestroyOnLoad(obj);
instance = obj.AddComponent<T>();
}
return instance;
}
}
测试脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : SingletonAutoMono<NewBehaviourScript>
{
public void Test()
{
Debug.Log(NewBehaviourScript.GetInstance().name);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
NewBehaviourScript.GetInstance().Test();
}
}