商城網(wǎng)站源碼下載seo排名軟件有用嗎
Unity3D 泛型單例
單例模式
單例模式是一種創(chuàng)建型設(shè)計模式,能夠保證一個類只有一個實(shí)例,提供訪問實(shí)例的全局節(jié)點(diǎn)。
通常會把一些管理類設(shè)置成單例,例如 GameManager
、UIManager
等,可以很方便地使用這些管理類單例,存儲變量和調(diào)用接口。
手動掛載的泛型單例
創(chuàng)建 SingletonMono.cs
腳本,在類名后面添加泛型和約束,定義泛型變量,并且在 Awake
方法中對變量進(jìn)行賦值。
這里的 Awake
方法是虛方法,當(dāng)有管理類繼承這個 SingletonMono
時,可以重寫 Awake
方法進(jìn)行額外的操作。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{static T instance; // 私有靜態(tài)實(shí)例public static T Instance { get { return instance; } } // 公開實(shí)例屬性protected virtual void Awake(){if (instance == null){instance = this as T;// 切換場景時不銷毀這個游戲物體DontDestroyOnLoad(gameObject);}else{// 切換場景時,如果場景里有單例游戲物體,在已經(jīng)創(chuàng)建單例的情況下,銷毀多余的游戲物體Destroy(gameObject);}}
}
創(chuàng)建 GameManager.cs
腳本,繼承 SingletonMono
這個類。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class GameManager : SingletonMono<GameManager>
{public int score;protected override void Awake(){// 調(diào)用基類的 Awake 方法base.Awake();// 可以進(jìn)行額外的初始化操作score = 0;}void Start(){}void Update(){}
}
在場景中創(chuàng)建游戲物體,把 GameManager
腳本手動掛載到游戲物體上。
創(chuàng)建 SingletonTest.cs
腳本,簡單使用一下 GameManager.Instance
單例的變量。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class SingletonTest : MonoBehaviour
{void Start(){int score = GameManager.Instance.score;Debug.Log($"score = {score}");}
}
運(yùn)行游戲,可以看到 GameManager
在 DontDestroyOnLoad
場景中,可以獲取到 score
變量進(jìn)行打印。
自動掛載的泛型單例
創(chuàng)建 SingletonMonoAuto.cs
腳本,在類名后面添加泛型和約束,定義泛型變量。
因?yàn)樗⒉恍枰趫鼍爸惺謩觿?chuàng)建游戲物體,也不會通過 Awake
方法對變量進(jìn)行賦值。
所以在獲取 Instance 屬性時,如果屬性為空,就通過代碼創(chuàng)建一個不會銷毀的游戲物體,并自動掛載單例組件。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class SingletonMonoAuto<T> : MonoBehaviour where T : MonoBehaviour
{static T instance; // 私有靜態(tài)實(shí)例// 公開實(shí)例屬性public static T Instance{get{if (instance == null){// 創(chuàng)建一個新的游戲物體GameObject obj = new GameObject();// 根據(jù)類型進(jìn)行重命名obj.name = typeof(T).ToString();// 自動掛載單例組件instance = obj.AddComponent<T>();// 不可銷毀DontDestroyOnLoad(obj);}// 返回實(shí)例return instance;}}
}
創(chuàng)建一個 UIManager.cs
腳本,繼承 SingletonMonoAuto
這個類。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class UIManager : SingletonMonoAuto<UIManager>
{void Awake(){Debug.Log("初始化 UIManager");}void Start(){}void Update(){}
}
在 SingletonTest.cs
腳本,簡單使用一下 UIManager.Instance
單例。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class SingletonTest : MonoBehaviour
{void Start(){int score = GameManager.Instance.score;Debug.Log($"score = {score}");UIManager uiManager = UIManager.Instance;}
}
運(yùn)行游戲,可以看到 UIManager
在 DontDestroyOnLoad
場景中自動創(chuàng)建。