简体   繁体   中英

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()
    {
    }
}

I can't use the GetMonsterinfo method in the PatrolState Class

I want to pass the skeleton or other monster , so I don't have to write a lot of status code

You can implement a new interface as below:

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()
    {
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM