I know, I know… This has been asked all over the place, but I personal don’t get it. Could someone help me out. I am trying to use my Ammo_Size float from my first script and use it in my gun script so I can compare the Ammo_Size number in the gun script.
Gun Script:
void Start()
{
Ammo_Clip ammo_clip = GetComponent<Ammo_Clip>();
}
public void Update()
{
if (ammo_clip.Clip_Size > 0)
{
Gun_Controll();
}
}
Ammo_Clip Script:
public float Ammo_Size;
public float Clip_Size;
public Text Ammo_Clip_Display;
private void Start ()
{
Ammo_Size = 36;
Clip_Size = 12;
Display_Ammo_Clip();
}
Please don’t post a comment/follow-up as an Answer - use the “Add comments” button or the “reply” link instead; I fixed this for you.
You need to fix 4 to be something like
Ammo_Clip ammo_clip = GameObject.Find("myThing").GetComponent<Ammo_Clip>();
TBruce
3
Hi @Nova_Tech,
This is your error
if (ammo_clip.Clip_Size > 0)
The reason you are getting an error is that ammo_clip is null. The reason it is null is because you have not attached a Ammo_Clip to the game object that the Gun Script component is attached to.
To fix this first make sure that ammo_clip is posted as a global like so
private Ammo_Clip ammo_clip;
Now in the Start() function set the ammo_clip reference like so
void Start()
{
ammo_clip = GetComponent<Ammo_Clip>();
}
Now when you go to you the ammo_clip do the following to ensure that you do not get an error
public void Update()
{
// make sure that ammo_clip is valid before trying to use it
if ((ammo_clip != null) && ammo_clip.Clip_Size > 0))
{
Gun_Controll();
}
}