我正试图在我的Unity3d项目中实现一个Singleton基类。但是,试图访问Singleton实例会引发编译器错误:
Type 'Singleton' does not contain a definition for 'getPlaneTextureType' and no extension method 'getPlaneTextureType' of type 'Singleton' could be found (are you missing a using directive or an assembly reference?)
对于从Singleton派生的每个类,我是否需要重写方法/属性instance ,即,将返回类型更改为子类类型?或者,我可以对基类Singleton进行一个简单的更改来修复这个问题吗?例如,使用类似于c++的模板?
public class Singleton : MonoBehaviour {
#region Static Variables
private static Singleton _instance = null;
#endregion
#region Singleton Class Generation
public static Singleton instance {
get { return _instance; }
}
protected Singleton() { }
void Awake() {
if (_instance != null) {
GameObject.Destroy( this );
return;
}
_instance = this;
}
#endregion
}
public class TerrainManager : Singleton {
public PlaneTexture getPlaneTextureType() { }
}
// Usage that throws compiler error: Type 'Singleton' does not contain a definition for 'getPlaneTextureType' and no extension method 'getPlaneTextureType' of type 'Singleton' could be found (are you missing a using directive or an assembly reference?)
TerrainManager.instance.getPlaneTextureType();发布于 2014-06-05 05:21:18
有时,您希望统一中的Singleton只是一个普通的Singleton设计模式,而不是一个MonoBehaviour。
其他时候,你需要你的单身成为一个MonoBehaviour。当它必须是MonoBehaviour时,您可以这样做,以避免调用new (在MonoBehaviours上不能这样做)。
解决方案
用MonoBehaviour制作一个单例
public class Singleton : MonoBehaviour
{
private static Singleton _instance;
// Will be called before anything, don't even worry about it, instance be initialized.
void Awake()
{
_instance = this;
}
public static Singleton getInstance()
{
return _instance;
}
}这还应该允许您从这个Singleton继承如下:
public class Singleton2 : Singleton
{
}另外,您使用的Destroy()代码不是一个好主意,除非您正在用DontDestroyOnLoad()保护Singleton在级别更改时不被销毁。
其他解决方案
您可以在这里找到它:团结Wiki Singleton,它是Imran发布的相同的代码,但是他忘了包括他从哪里得到它的参考链接。
https://stackoverflow.com/questions/24051805
复制相似问题