0
votes

I have a list of enemys. so i want each enemy have their turn. First of all : Player turn --> enemys turn ("here each enemy move one by one untill the end then player move again"). how do i making some waiting time here and forcus on enemy turn? Any help would be appreciated.

void Start()
{
     // find list enemy
    enemy = GameObject.FindGameObjectsWithTag("Enemy");

}
void Update()
{
    //enemy turn reference to player. after move all enemy we change it to false to change the player turn.
    if(StaticClass.enemyTurn == true )
    {
       for(int i=0;i<enemy.length;i++)
        {
           // how do i making some waiting time here and forcus on enemy turn?
           EnemyTurn(i);
        }
    }
}


 public void EnemyTurn(int id)
{
    ChessMoveMent chessMoveScript = enemy[id].GetComponent<ChessMoveMent>();
    chessMoveScript.ProcessMove();
    id++;
    if(id>=enemy.Length)
    {
        isMove = false;
    }
}
2

2 Answers

0
votes

I usually use StartCoroutine in this case. Please try the below code:

public IEnumerator EnemyTurn(int id)
{
  yield return null;
  ChessMoveMent chessMoveScript = enemy[id].GetComponent<ChessMoveMent>();
  chessMoveScript.ProcessMove();
  id++;
  if(id>=enemy.Length)
  {
    isMove = false;
  }
}

When you want to use it, please use with "StartCoroutine()"

StartCoroutine(EnemyTurn(i));

More details here

0
votes

You might have a coordinator, who tells the participants when it's their turn.

public class GameCoordinator : MonoBehaviour
{
    public List<Participant> participants;
    private int currentParticipantIdx = -1;

    private Participant CurrentParticipant
    {
        get { return participants[currentParticipantIdx]; }
    }

    private void Start()
    {
        PlayNextMove();
    }

    private void PlayNextMove()
    {
        ProceedToNextParticipant();

        CurrentParticipant.OnMoveCompleted += OnMoveCompleted;
        CurrentParticipant.BeginMove();
    }

    private void OnMoveCompleted()
    {
        CurrentParticipant.OnMoveCompleted -= OnMoveCompleted;
        StartCoroutine(PlayNextMoveIn(2.0f));
    }

    private IEnumerator PlayNextMoveIn(float countdown)
    {
        yield return new WaitForSeconds(countdown);
        PlayNextMove();
    }

    private void ProceedToNextParticipant()
    {
        ++currentParticipantIdx;
        if (currentParticipantIdx == participants.Count)
            currentParticipantIdx = 0;
    }
}

public class Participant : MonoBehaviour
{
    public event Action OnMoveCompleted;

    public void BeginMove()
    {
        //
    }
}