Unity单例类
代码块
using UnityEngine;
public class Singleton
{
private static Singleton _instance = null;
public static Singleton Instance
{
get
{
if (Singleton._instance == null)
{
Singleton._instance = new Singleton();
}
return _instance;
}
}
//测试方法
public void Say()
{
Debug.Log("I am Singleton class");
}
}
unity组件单例
代码块
public class SingleCom : MonoBehaviour
{
public static SingleCom Instance;
private void Awake()
{
Instance = this;
}
void Start()
{
}
public void Say()
{
Debug.Log("I am SingleCom");
}
}
Cocos单例类
代码块
export class Singleton {
private static _instance: Singleton | null = null;
public static get Instance() {
if (Singleton._instance == null) {
Singleton._instance = new Singleton()
}
return Singleton._instance;
}
say(){
console.log(" I am singleton class")
}
}
Cocos组件单例

代码块
import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('SingletonCom')
export class SingletonCom extends Component {
public static Instance: SingletonCom | null = null;
onLoad() {
if (SingletonCom.Instance && SingletonCom.Instance !== this) {
this.node.destroy();
return;
}
SingletonCom.Instance = this;
}
say() {
console.log("I am singleton com")
}
}
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删