alexo1001
alexo1001

Reputation: 307

Trying to make the program wait for a number of seconds and then continuing in C# using Unity

I was writing some code to make an AI shoot forwards but the AI shoots so fast that it will hit it's own bullets and they will explode. I have tried to add a delay in between but I do not know how to do it. Here is the part of my code in which I need it. Please help, thanks!

private void Start()
{
    m_FireButton = "Fire" + m_PlayerNumber;

    m_ChargeSpeed = (m_MaxLaunchForce - m_MinLaunchForce) / m_MaxChargeTime;
}

void OnTriggerStay(Collider other) {
    if (other.tag == "Player")  {
        Fire ();
        //This is where I want to add a delay!
    }
}

Upvotes: 1

Views: 377

Answers (1)

Everts
Everts

Reputation: 10721

For this to happen properly you need to think why it fails. The reason is that OnTriggerStay is called for each FixedUpdate the player is within the collider.

What you want is a different approach.

private bool isInside = false;
void OnTriggerEnter(Collider col){
    if(col.gameObject.CompareTag("Player") == false){ return; }
    isInside = true;
    Fire();
}
void OnTriggerExit(Collider col){
    if(col.gameObject.CompareTag("Player") == false){ return; }
    isInside = false;
    timer  = 0f;
}
private float timer = 0f;
private float waitTime = 0.2f;
void Update(){
    if(isInside == false) { return; }
    if(timer > waitTime){
        timer = 0f;
        Fire();
    }
    timer += Time.deltaTime;
}

Upvotes: 1

Related Questions