简体   繁体   中英

delay on the shot every 3 seconds in unity using c#

sorry guys I'm new to c# and unity... what I want there is to execute spawner.SendMessage("shoot"); every 3 seconds.. it'll only execute once the condition is met.

    void Update(){

    //first we draw a line from our enemy to our player
    Debug.DrawLine (player.position, myTransform.position, Color.red);

    playerDistance = Vector3.Distance(player.position, myTransform.position);
    if (playerDistance < 40f) {

        lookAtPlayer ();

    }

    if(playerDistance <= 38f){
        if(playerDistance > 21){
            //move towards the player
            myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;

            spawner.SendMessage("shoot");


        }
    }
}

Let me get this straight, is this for an NPC type object? Are you building an Enemy AI?

If you just want him to shoot every 3 seconds while moving towards the target the following code should suffice:

float timer;

void Start()
{
    timer = 0;
}

void Update()
{
    timer += Time.deltaTime;

    if (playerDistance <= 38 && playerDistance > 21)
    {
          myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
          if (timer > 3.0f)
          {
              spawner.SendMessage("shoot");
              timer = 0;
          }
    }
}

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