Объект спамится, когда дело доходит до моей переменной timeBetweenShot, может кто-нибудь взглянуть? - PullRequest
0 голосов
/ 11 января 2019

Я создал 2-ую игру-невидимку, в которой враг стреляет по игроку, единственная проблема в том, что хотя пули создаются и удаляются удачно в другом скрипте, сам скрипт спамит программой пули в каждом кадре, создавая нежелательный результат

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HurtPlayer : MonoBehaviour
{

public float timeToShoot;
private float timeToShootCounter;
private bool shot;
private Vector3 moveDirection;
public float timeBetweenShot;
public float timeBetweenShotCounter;

public Transform firePoint;
public GameObject Bullet;



// Use this for initialization
void Start()
{
    shot = false;
    timeToShootCounter = timeToShoot;


}
// Update is called once per frame
void Update()
{
    while (shot == true)
    {
        StartCoroutine(Delay());
        Destroy(GameObject.Find("Bullet"));
        timeBetweenShot -= Time.deltaTime;
        timeToShoot -= Time.deltaTime;
    }


}

IEnumerator Delay()
{
    yield return new WaitForSeconds(0.5f);
}

void OnTriggerStay2D(Collider2D other)
{
    if (other.gameObject.tag == "player")
    {
        if (shot == false)
        {

            if (timeToShoot >= 0f)
            {
                shot = true;
                if (shot == true)
                {
                    shot = false;
                    Instantiate(Bullet, firePoint.position, firePoint.rotation);

                    Delay();
                    if (timeBetweenShot <= 0f)
                    {
                        shot = false;
                        timeToShoot = timeToShootCounter;
                        timeBetweenShot = timeBetweenShotCounter;
                    }
                }

            }
        }
    }
}

}

То, что я хочу, это время между выстрелом, чтобы противник стрелял только раз в полторы секунды, спасибо.

1 Ответ

0 голосов
/ 11 января 2019

Это то, что вы ищете?

IEnumerator ContinuousShoot()
{
    // Continuously spawn bullets until this coroutine is stopped
    // when the player exits the trigger.
    while (true)
    {
        yield return new WaitForSeconds(1f); // Pause for 1 second.
        Instantiate(Bullet, firePoint.position, firePoint.rotation);
    }
}

void OnTriggerEnter2D(Collider2D other)
{
    // Player enters trigger
    if (other.gameObject.CompareTag("player"))
    {
        StartCoroutine(ContinuousShoot());
    }
}

void OnTriggerExit2D(Collider2D other)
{
    // Player exits trigger
    if (other.gameObject.CompareTag("player"))
    {
        StopCoroutine(ContinuousShoot());
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...