Reputation:
I wan't to create a shooting script referencing a ammo script i made earlier. I wan't the shooting script to shoot only when ammo is equal or less than Max ammo but has more than 0. I tried to make the ammo and maxammo a public static int in the ammo script and a private static int in the shooting script but it dosen't seem to work. Is there a problem with the refrence or is there a problem with the script itself.
Ammo:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Ammo : MonoBehaviour
{
public static int Ammocount;
public static int Maxammo;
public float Magazines;
public Text AmmoCounter;
public Text MagazinesUI;
private string AmmointoString;
private string MagazinesintoString;
// Start is called before the first frame update
void Start()
{
Ammocount = 6;
Maxammo = 6;
Magazines = 10;
}
// Update is called// once per frame
void Update()
{
// Transforms a int into a string and also it makes the ammo a part of the UI
MagazinesintoString = Magazines.ToString();
AmmointoString = Ammocount.ToString();
AmmoCounter.text = AmmointoString;
MagazinesUI.text = MagazinesintoString;
//If you have ammo and you press mouse one ammo deacreses and if you have less than 6 bullets you
if (Ammocount <= Maxammo && Input.GetButtonDown("Fire1") && Ammocount > 0)
{
Ammocount -= 1;
}
else if (Ammocount < Maxammo)
{
if (Input.GetKeyDown("r") && Magazines > 0)
{
Ammocount = 6;
Magazines -= 1;
}
}
}
}
Gun Script:
using UnityEditor;
using UnityEngine;
public class Gunscript : MonoBehaviour
{
public float Damage = 10f;
public float Range = 100f;
public ParticleSystem muzzleflash;
public Camera Fpscam;
private AudioSource gunshot;
public GameObject Pistol;
private static int ammo;
private static int maxammo;
void Start()
{
ammo = Ammo.Ammocount;
maxammo = Ammo.Maxammo;
gunshot = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1") && ammo <= maxammo && ammo > 0)
{
muzzleflash.Play();
Shoot();
gunshot.Play(0);
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(Fpscam.transform.position, Fpscam.transform.forward, out hit, Range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(Damage);
}
}
}
}
}
Upvotes: 0
Views: 81
Reputation: 90580
int
is a VALUE type ... not a reference ... therefore updating the value in the Ammo
class doesn't automatically update it for the Gunscript
class!
You should rather remove your local fields from Gunscript
private static int ammo;
private static int maxammo;
and directly use
// Afaik comparing the int is cheaper then getting Input
// You should do the cheaper checks first
if (Ammo.Ammocount <= Ammo.Maxammo && Ammo.Ammocount > 0 && Input.GetButtonDown("Fire1"))
{
muzzleflash.Play();
Shoot();
gunshot.Play(0);
}
Upvotes: 2