I am trying to make an ammo system in unity but it will not work. The Problem Is That I Can Keep Destroying The Aestroid Even When My Ammo Runs Out.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ExplosionOnTouch : MonoBehaviour
{
// Start is called before the first frame update
public int Ammo = 10;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (Ammo > 0)
{
Ammo = Ammo - 1;
Destroy(gameObject);
}
else
{
SceneManager.LoadScene("DeathScreen", LoadSceneMode.Single);
}
}
}
CodePudding user response:
Your Ammo will never become zero. Your script lifecycle now is:
- create an object
- set
Ammoto 10 on creation - decrease
Ammoon collision and destroy object withAmmocount 9
So you need to move your Ammo count to one place and to make all scripts decrease one common counter instead of unique for every object. For example, to the script that creates your bullets. It will be much more logical.
