【发布时间】:2016-05-05 07:04:59
【问题描述】:
在我的项目中,我有一个如图所示的类结构。
绿色类是旧代码,运行良好。红框中的类是新添加的代码。没有编译错误,但是在Unity中点击play运行到新代码时,三个类不能正确初始化。
并且统一控制台发出警告说“名为'DataMgrBase`2'的类是通用的。不支持通用的MonoBehaviours!UnityEngine.GameObject:AddComponent()”在这一行:“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);
}
}
}
【问题讨论】:
标签: c# generics unity3d unity5