Home > Mobile >  How to generic pass class as parameter
How to generic pass class as parameter

Time:12-03

public class Skeleton : Monster
{
    private MonsterBaseState state;
    private void Awake()
    {
        state = new PatrolState<Skeleton>(this);
    }
    public void  GetMonsterInfo()
    {
      dosomething;
    }
}
pubilc class ManyMonster:Monster 
{
    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

CodePudding user response:

You can implement interface IMonster 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()
    {
    }
}
  • Related