我查看了代码并多次尝试了不同的方法,但我似乎无法让它发挥作用。
它正常工作两次,然后第三次停止正常工作。
我希望每次都能实例化一个对象,但是第三次它会生成30个,这很糟糕。
我希望它每次都能产生1个对象。
所以我使用了这个脚本。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Attack : MonoBehaviour {
public Transform playerPos = null;
private float playerDist;
private GameObject projectileEnemyClone;
public GameObject projectileEnemyPrefab;
private float kickBack = 10;
private Rigidbody rb;
private int bulletCount = 0;
private bool canshoot = true;
void Start()
{
rb = GetComponent<Rigidbody>();
}
private void Shoot()
{
if (canshoot == true)
{
projectileEnemyClone = Instantiate(projectileEnemyPrefab, transform.position, Quaternion.identity) as GameObject;
canshoot = false;
}
}
private void Respawn()
{
canshoot = true; ;
}
private void ShootLeft()
{
Shoot();
projectileEnemyClone.transform.position = new Vector3(transform.position.x - 1, transform.position.y, transform.position.z);
projectileEnemyClone.GetComponent<Rigidbody>().AddForce(transform.right * -10);
kickBack *= -1;
rb.AddForce(transform.right * kickBack);
Destroy(projectileEnemyClone, 1);
if (!canshoot)
{
Invoke("Respawn", 2);
}
}
private void ShootRight()
{
Shoot();
projectileEnemyClone.transform.position = new Vector3(transform.position.x + 1, transform.position.y, transform.position.z);
projectileEnemyClone.GetComponent<Rigidbody>().AddForce(transform.right * 10);
rb.AddForce(transform.right * kickBack);
Destroy(projectileEnemyClone, 1);
Invoke("Respawn", 2);
}
void Update () {
playerDist = playerPos.position.x - transform.position.x;
if (playerDist <= (3) && playerDist >= (-3))
{
if (playerDist < (0))
{
Invoke("ShootLeft", 1);
}
else
{
Invoke("ShootRight", 1);
}
}
}
}
答案 0 :(得分:0)
不要使用Invoke(),你应该创建一个控制你的Shoot()函数的计时器。
float shootCooldown = 0.1f;
float shootTimer = 0;
bool justShot = false;
void Update()
{
if(!canShoot)
{
shootTimer += Time.deltaTime;
if(shootTimer >= shootCooldown)
{
shootTimer = 0;
canShoot = true;
}
}
}
void Shoot()
{
if(canShoot)
{
Shoot();
canShoot = false;
}
}