2015-02-11 20 views
0
class A 
{ 
    public static A Instance {get; private set;} 

    protected virtual void Awake() 
    { 
     Instance = this; 
    } 
} 

class B : A 
{ 
    protected override void Awake() 
    { 
     base.Awake(); 
    } 

    public void Bmethod() 
    { 
     //do smth 
    } 
} 

class C 
{ 
    private void SomeMethod() 
    { 
     B.Instance.Bmethod(); 
    } 
} 

所以,這就是例子。我知道這是不可能的。 我的問題是我怎樣才能以類似的方式實現這一目標,而不是太長?如何即興創建單身繼承類?

我想出了一個主意,但仍然認爲必須有另一個,更好。

class C 
{ 
    private void SomeMethod() 
    { 
     B.Instance.gameObject.GetComponent<B>().Bmethod(); 
    } 
} 
+0

一種方法是在派生類創建實例變量。但是這意味着如果我有104238個派生類,我將不得不創建104238個實例變量。所以它可以工作,但它不是有效的。 – ZenVentzi 2015-02-11 06:35:42

回答

1

我總是有一個泛型類來創建我的單例。我首先創建一個抽象類,如下所示:

using UnityEngine; 

public abstract class MySingleton<T> : ClassYouWantToInheritFrom where T : MySingleton<T> 
{ 
    static T _instance; 
    public static T Instance 
    { 
     get 
     { 
      if(_instance == null) _instance = (T) FindObjectOfType(typeof(T)); 
      if(_instance == null) Debug.LogError("An instance of " + typeof(T) + " is needed in the scene, but there is none."); 
      return _instance; 
     } 
    } 

    protected void Awake() 
    { 
     if  (_instance == null) _instance = this as T; 
     else if(_instance != this) Destroy(this); 
    } 
} 

現在,您將此腳本放置在項目的某個位置並且再也不要觸摸它。

從MySingleton <創建一個繼承ClassYouWantToInheritFrom單身,你讓你的類繼承MyClass的>,而不是僅僅ClassYouWantToInheritFrom,因爲MySingleton已經繼承了它。 就這樣:

public class MyClass : MySingleton<MyClass> 
{ 
} 

,而不是

public class MyClass : ClassYouWantToInheritFrom 
{ 
} 

希望這有助於:)