Hey peeps,
I am making a moible game. I may have gone about setting up the scripts wrong in terms of what they are attached to so please advise if so.
I have a script attached to the attack button which includes my fire script and ammo counter which refers to a ui text box.
I also have a script attached to an ammo box that when picked up I want to change the ammo value within the attack script (attached to the attack button on the canvas).
The script I show here works in terms of no syntax errors and the script reference and int reference are found while coding. However when the player collects the ammo box I get that message “Object reference not set to an instance of an object” for the following code:
public class Ammo : MonoBehaviour {
public int ammoValue = 150;
void OnCollisionEnter(Collision hit){
if (hit.gameObject.tag == "Player")
{
DestroyObject(gameObject);
Debug.Log ("Collected Ammo");
GameObject.Find ("Canvas").GetComponent<PrimaryAttack> ().gunAmmo += ammoValue;
}
}
}
Here is the code attached to my attack button within the Canvas:
public class PrimaryAttack : MonoBehaviour, IPointerUpHandler, IPointerDownHandler {
public bool butt1down;
public Transform firepoint;
public float fireSpeed = 15f;
private float waitnextFire = 0f;
public int gunAmmo = 500;
public Text gunam;
// Use this for initialization
private void Start () {
if (firepoint == null)
{
Debug.Log ("No firepoint found");
}
}
public virtual void OnPointerDown(PointerEventData ped)
{
butt1down = true;
}
public virtual void OnPointerUp(PointerEventData ped)
{
butt1down = false;
}
void Fire()
{
GameObject obj = NewObjectPooler.current.GetPooledObject ();
if (obj == null)
return;
obj.transform.position = firepoint.position;
obj.transform.rotation = firepoint.rotation;
obj.SetActive (true);
}
void Update(){
if (butt1down == true)
{
if (waitnextFire <= 0 && gunAmmo > 0)
{
Fire ();
waitnextFire = 1;
gunAmmo -= 1;
}
}
waitnextFire -= Time.deltaTime * fireSpeed;
gunam.text = gunAmmo.ToString ();
}
}
Thank Yous!!! ![]()