Help with Ammo UI C#
Hello! I'm fairly new at Unity so I hope it's not some stupid mistake, but I'm trying to update my UI to show the ammo for the weapon I'm using. Example: "12/12" to "12/11" I've done Health Bar UI but for some reason the ammo is giving me issues by giving me the "Object reference not set" error. Here is the Ammo Bar script:
public class AmmoBar : MonoBehaviour {
public Image ammo;
public Text ammoAmount;
WeaponManager wm;
Weapons wpn;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnGUI()
{
ammoAmount.text = (wm.currentAmmo + "/" + wpn.maxAmmo);
}
}
I have this script accessing two other scripts I have, Weapons and WeaponsManager the Weapons contains the max ammo for that specific weapon(I can change the values per weapon), and the WeaponsManager contains the current ammo which is set to that weapons max ammo at start.
The reloading works, I have a Debug Log telling me the ammo counts down and reloads on WeaponsManager, I've even got the "12/12" to "12/11" to work in the Debug Log on that script, however I cannot get it to work on this one. I've tried the code on both the Update and OnGUI as well; I don't know how its not finding what I've given it the information to. Thanks for your time!
Answer by RawallonCG · Mar 27, 2018 at 03:50 AM
The script doesn't know what wm/wpn is supposed to be so you either need to drag and drop them using the editor (for that to be shown you'ld need to use SerializeField) or assign it on the start of the script (or on Awake if you're going to have this script repeated too many times)
void Start () {
wm = Object.FindObjectOfType<WeaponManager>();
wpn = Object.FindObjectOfType<Weapons>();
}
Worth keeping in mind that you can also use
something = GameObject.FindGameObjectWithTag ("something ").GetComponent<something>();
Your answer
![](https://koobas.hobune.stream/wayback/20220612154946im_/https://answers.unity.com/themes/thub/images/avi.jpg)