只实例化一次,减少内存占用
普通脚本单例
/**
*Copyright(C) 2015 by #COMPANY#
*All rights reserved.
*Author: RenHao
*Version: 1.0
*Date: 2020-09-12 15:28:59
*Description:
*History:
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
///
/// <summary>
public class SceneMgr
{
private static SceneMgr _Instance;
public static SceneMgr Instance
{
get
{
if (_Instance == null)
{
_Instance = new SceneMgr();
}
return _Instance;
}
}
public void TestLog()
{
Debug.Log("执行单例");
}
}
3D物体单例
/**
*Copyright(C) 2015 by #COMPANY#
*All rights reserved.
*Author: RenHao
*Version: 1.0
*Date: 2020-09-12 15:42:20
*Description:
*History:
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
///
/// <summary>
public class TestCtrl : MonoBehaviour
{
private static TestCtrl _Instance;
public static TestCtrl Instance
{
get
{
if (_Instance == null)
{
GameObject obj = new GameObject("TestCtrl");
_Instance = obj.AddComponent<TestCtrl>();
DontDestroyOnLoad(obj);
}
return _Instance;
}
}
public void TestLog()
{
Debug.Log("执行了TestCtrl方法");
}
}
如果全局唯一
public static TestScene Instance;
void Awake(){
Instance = this;
}