簡體   English   中英

如何通用傳遞 class 作為參數

[英]How to generic pass class as parameter

public class Skeleton : MonoBehaviour
{
    private MonsterBaseState state;
    private void Awake()
    {
        state = new PatrolState<Skeleton>(this);
    }
    public void  GetMonsterInfo()
    {
      dosomething;
    }
}
pubilc class manyMonster:MonoBehaviour 
{
    private MonsterBaseState state;
    private void Awake()
    {
        state = new PatrolState<Skeleton>(this);
    }
}
//and more monster Class

public interface MonsterBaseState
{
    void BehaviorForUpdate();
}
public class PatrolState<T> : MonsterBaseState
{ 
    private T cluster;
    public PatrolState(T curCluster)
    {
        cluster = curCluster;
        cluster.GetMonsterInfo();//wrong here
    }
        public void BehaviorForUpdate()
    {
    }
}

我不能在 PatrolState Class 中使用 GetMonsterinfo 方法

我想通過骷髏或者其他怪物,所以不用寫很多狀態碼

您可以實現一個新接口,如下所示:

public interface IMonster
{
    void GetMonsterInfo();
    //void MonsterMethod1();
    //void MonsterMethod2();
    //..
}

public class Skeleton : MonoBehaviour,IMonster
{
    private MonsterBaseState state;
    private void Awake()
    {
        state = new PatrolState<Skeleton>(this);
    }
    public void  GetMonsterInfo()
    {
       
    }

}


public interface MonsterBaseState
{
    void BehaviorForUpdate();
}
public class PatrolState<T> : MonsterBaseState where T :IMonster
{ 
    private T cluster;
    public PatrolState(T curCluster)
    {
        cluster = curCluster;
        cluster.GetMonsterInfo();//wrong here
    }
    
    public void BehaviorForUpdate()
    {
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM