Hello coding elders!
I’ve been trying to make a small tank game, and I have made my shooting and reloading scripts as coroutines, as think this may be the most efficient method for my game.
The issue is that the parameters dont update/change when i use the parameter name in the script, but if i use the variable name directly, it works fine. IE the ammo variable wont be changed if i use the parameter. This could kind of work, but it breaks the functionality of coroutines/functions.
Here is the code I’m working on, and I’ve cut out most unnecessary stuff.
Edit: Thanks MJ, i dont know how the code snippet got that messed up! :l, It should be fixed now…
public class BasicShell : MonoBehaviour
{
public GameObject prefabStandardShell;
public float shotSpeed = 2000;
public float fallSpeed = 2700;
public Transform originPos;
public int fullMagAmmo = 25;
public int magAmmo = 25;
public float reloadTime = 0.5f;
public float range = 1;
public bool reloading;
// Update is called once per frame
private void Update()
{
if (magAmmo == 0)
{
StartCoroutine(ReloadWaitTime(reloadTime, magAmmo));
}
if (Input.GetKeyDown(KeyCode.Mouse0) == true && magAmmo != 0)
{
StartCoroutine(Fire(magAmmo));
}
}
public IEnumerator Fire(int ammo)
{
ammo -= 1;
GameObject shellInstance = (GameObject)Instantiate(prefabStandardShell, originPos.position, originPos.rotation);
shellInstance.GetComponent<Rigidbody>().AddForce(originPos.up * shotSpeed);
yield return new WaitForSeconds(range);
// make the shell fall after range
shellInstance.GetComponent<Rigidbody>().AddForce(originPos.forward * -fallSpeed);
}
public IEnumerator<float> ReloadWaitTime(float waitTime, int ammo)
{
yield return Timing.WaitForSeconds(waitTime);
ammo = fullMagAmmo;
// reloading = false;
print("reloaded");
yield break;
//StopCoroutine("ReloadWaitTime");
}
}
But if i do this:
public IEnumerator Fire(int ammo)
{
magAmmo -= 1;
it works fine. Sorry to post a mouthfull of code for a simple question, but i want to be clear off the bat :).
Thank you for viewing!