在我的項目中,我有一個類結構,如圖所示。
綠色班是舊的代碼,運行得很好。紅色框中的類是新添加的代碼。沒有編譯器錯誤,但是當單擊Unity中的播放並運行到新代碼中時,三個類無法正確初始化。
Unity控制檯給出了警告:「名爲'DataMgrBase`2'的類是通用的,不支持通用MonoBehaviours!」在這一行:「instance = obj.AddComponent(); 「
我該如何解決這個問題?
以下是一些供您參考的代碼,謝謝!
實現單基類:
using UnityEngine;
using System.Collections;
public class UnitySingletonPersistent<T> : MonoBehaviour where T : Component
{
private static T instance;
public static T Instance {
get {
if (instance == null) {
instance = FindObjectOfType<T>();
if (instance == null) {
GameObject obj = new GameObject();
obj.name = typeof(T).Name;
obj.hideFlags = HideFlags.DontSave;
instance = obj.AddComponent<T>();
}
}
return instance;
}
}
public virtual void Awake()
{
DontDestroyOnLoad (this.gameObject);
if (instance == null) {
instance = this as T;
} else {
Destroy (gameObject);
}
}
}
DataMgrBase的執行情況:
public class DataMgrBase<TKey, TValue>: UnitySingletonPersistent<DataMgrBase<TKey, TValue>> {
protected Dictionary<TKey, TValue> dataDict;
public override void Awake()
{
base.Awake();
dataDict = new Dictionary<TKey, TValue>();
}
public TValue GetDataForKey(TKey key)
{
TValue data;
if (dataDict.TryGetValue(key, out data))
{
return data;
}
else
{
data = LoadDataForKey(key);
if (data != null)
{
dataDict.Add(key, data);
}
return data;
}
}
virtual protected TValue LoadDataForKey(TKey key)
{
if (dataDict.ContainsKey(key))
{
return GetDataForKey(key);
}
else
{
return default(TValue);
}
}
}
這是很酷的解決方法,但是我有一點小小的感覺,那就是Unity3D的做事方式。無論如何,祝賀你解決問題! –
謝謝:) @JerrySwitalski – ArtS