Please Help figure out whats wrong with Ammo Counter.

Hi, trying to figure out why the ammo script I’m building isn’t working. It’s a C# script for Unity 5.3 and I’m trying to build a script that does a score counter of 5 attached to a UI.Text attached to the canvas. Final score counter in camera view should be Ammo : 5 with the 5 decreasing with every shot. AmmoGUItext is the name of the UI.Text component.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class AmmoCounter : MonoBehaviour {

	int Ammo = 5;
	public UIText AmmoGUItext;

	void Update()
{
	if(Ammo != 0) 
	{
	if(Input.GetButtonUp("Fire1"))
		Ammo--;
	   }
	}
	void On() {
		AmmoGUItext.text = "Ammo: "Ammo");
    } 
}

Problem fixed:

using UnityEngine;


2.using System.Collections;


3.using UnityEngine.UI;


4. 


5.public class AmmoCounter : MonoBehaviour {


6. 


7.public int Ammo = 5;


8.public Text AmmoGUItext;


9. 


10.void Update()


11.{


12.   if(Ammo != 0 && Input.GetButtonUp("Fire1"))


13.   {


14.      Ammo--;


15.   }


16.}


17.void OnGUI()


18.{


19.   AmmoGUItext.text ="Ammo: " + Ammo);


20.}


21.}

Here’s cleaned up version of code provided :

 int Ammo = 5;
public Text AmmoGUItext;

void Start()
{
    AmmoGUItext.text = "Ammo : " + Ammo;
}

void Update()
{
    if (Input.GetButtonUp("Fire1") && Ammo > 0)
    {
        Ammo--;
        AmmoGUItext.text = "Ammo : " + Ammo;
    }
}

Update runs once per frame. We check if player has released button “Fire”, and if that is true, we also check if Ammo value is greater than 0. Only when both conditions are true our If block of code runs.

So we can use && to chain multiple conditions inside If statement.

In your original statement you check if value of Ammo is not 0. But that is also true if player has -6 ammo.

Finally we reduce Ammo value by one and update text property of Text component (which you need to drag to public field in Inspector). We first set value to “Ammo :” and then we add (convert to string) actual value of the ammo counter.

Where did you find type “UIText” by the way ?
Next time also include error that console reports back, when you try to run the game.