【发布时间】:2019-02-26 21:27:15
【问题描述】:
所以我最近一直在尝试制作游戏,但遇到了一个意想不到的错误。
当我运行我编写的脚本时,我可以从我的枪中射出 10 发子弹,然后它会播放重新加载声音并使用协程等待两秒钟,它会无缘无故地为我的剪辑添加 1200?所以我添加了 if 语句,告诉它如果剪辑大小超过 10,则将其恢复为 10,但现在它会在几秒钟内变为 19,然后又回到 10。
我不知道我是不是白痴还是什么,但很高兴能得到一些帮助,如果这是重复的,我也很抱歉,但我在 c# 中找不到类似的东西。
编辑:我现在已经修复了这个错误,感谢您的帮助,在旧代码之后分享新代码以供将来参考!
我的旧代码:
{
public float fireRate = 10;
public float damage = 15;
public int clipsize;
float timeUntilFire = 0;
public float ReloadSpeed = 2.5f;
float reloadtime;
public Transform firePoint;
public GameObject bullet;
public AudioSource gunshotaudio;
public AudioSource ReloadSound;
void Awake()
{
gunshotaudio = GetComponent<AudioSource>();
clipsize = 10;
}
// Update is called once per frame
void Update()
{
// if the button pressed is fire 1 and
if (Input.GetButtonDown("Fire1") && clipsize != 0)
{
timeUntilFire = Time.time / fireRate;
gunshotaudio.Play();
Shoot();
clipsize -= 1;
Debug.Log(clipsize);
}
if(clipsize <= 0)
{
ReloadSound.Play();
StartCoroutine(Wait());
StopCoroutine(Wait());
}
if(clipsize >= 11)
{
clipsize = 10;
}
}
IEnumerator Wait()
{
yield return new WaitForSecondsRealtime(2);
clipsize += 10;
}
void Shoot()
{
gunshotaudio.Play();
Instantiate(bullet, firePoint.position,firePoint.rotation);
}
} ** 我的新代码:**
{
public float fireRate = 10;
public float damage = 15;
public int clipsize;
float timeUntilFire = 0;
public float ReloadSpeed = 2.5f;
float reloadtime;
bool CanShoot;
bool IsReloading;
bool reloading;
public Transform firePoint;
public GameObject bullet;
public AudioSource gunshotaudio;
public AudioSource ReloadSound;
void Awake()
{
gunshotaudio = GetComponent<AudioSource>();
clipsize = 10;
}
void Start()
{
if (clipsize > 0)
{
CanShoot = true;
}
}
// Update is called once per frame
void Update()
{
// if the button pressed is fire 1 and
if (Input.GetButtonDown("Fire1") && clipsize != 0)
{
timeUntilFire = Time.time + fireRate;
gunshotaudio.Play();
Shoot();
clipsize--;
Debug.Log(clipsize);
}
// reloading
if(Input.GetKeyDown(KeyCode.R))
{
IsReloading = true;
ReloadSound.Play();
}
if (IsReloading)
{
StartCoroutine(Wait());
}
}
IEnumerator Wait()
{
if(reloading == false)
{
if (IsReloading)
{
reloading = true;
CanShoot = false;
yield return new WaitForSeconds(1);
clipsize = 10;
IsReloading = false;
Debug.Log(clipsize);
CanShoot = true;
reloading = false;
}
else
{
}
}
}
void Shoot()
{
gunshotaudio.Play();
Instantiate(bullet, firePoint.position,firePoint.rotation);
}
}
【问题讨论】:
-
您可能想要添加一个检查角色是否正在重新加载,如果他没有则只执行重新加载,我也不确定是否需要
StopCoroutine。 -
This 可能有帮助
-
所以我做了一些修改,当我射击时,我尝试重新加载并射击它会在我的剪辑中添加 129 个子弹,然后是 618 然后是 1217?