I'm having a bit of an odd issue in a 2d side-scroller game, where unity is only creating my projectile clone sometimes when pressing fire, it removes 1 grenade from the inventory correctly regardless of if the grenade is cloned or not. here is my code
void ThrowGranade()
{
if (grenandeInventory > 0)
{
GameObject grenade = Instantiate(projectile, projectileSpawnPoint.transform.position, Quaternion.identity) as GameObject;
grenandeInventory =- 1;
//am.ThrowGrenade();
}
else if (grenandeInventory <= 0)
{
grenandeInventory = 0;
}
}
and the fire button script held in the update function
if (Input.GetButtonDown("Fire1"))
{
if (grenandeInventory>0)
{
grenandeInventory -= 1;
ThrowGranade();
}
}
i add the force in the start function of the projectile itself
void Start () {
#region REFERENCES
anim = GetComponent<Animator>();
am = FindObjectOfType<AudioManager>();
rb = GetComponent<Rigidbody2D>();
player = FindObjectOfType<PlayerScript>();
capsule = GetComponent<CapsuleCollider2D>();
#endregion
rb.AddForce(Vector2.right * player.projectileForce, ForceMode2D.Force);
}
You shouldn't be doing the check in both your throw grenade method and when you click the button before calling the method. The way you set it up right now, if you have 1 grenade, you subtract from the grenade count before calling your throwGrenade so that your throwGrenade sees you have 0 grenades. Just do this.
if (Input.GetButtonDown("Fire1"))
{
ThrowGranade();
}
Your ThrowGranade() Method already handles the logic.