我正试图在我的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发布的相同的代码,但是他忘了包括他从哪里得到它的参考链接。
发布于 2014-06-05 05:12:18
您可以将getPlaneTextureType()方法移动到Singleton类中以使TerrainManager.instance.getPlaneTextureType()工作,您可以将getPlaneTextureType()转换为静态方法,并将其称为.TerrainManager.getPlaneTextureType()。
发布于 2014-06-05 05:12:29
继承不会帮助您在C#中很好地实现单例。原因是,如果将静态字段放置在基类中,则在所有继承的类中,它都是相同的静态字段。这正是你不想要的。您希望在每个继承的类中都有不同的静态字段和/或属性。
最初实现一个代码的代码并不多,所以继承并不能让您重用大量的代码。这是您的基本单例模板:
public class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton() { }
public static Singleton Instance { get { return instance; } }
}每次我需要的时候,我都会复制和粘贴它,但是我发现自己很少使用单例模式。
https://stackoverflow.com/questions/24051805
复制相似问题