I am trying to add a system to my game on Unity that makes it so that the player is able to pick up an ammo box and a value is randomly generated upon the pick up. I then want this randomly generated number to be used in my pistol script to add it onto the current ammo variable of the gun.
Below is the script I of what is done to the ammo box when it is interacted with by the player.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using static UnityEngine.Random;
public class AmmoController : MonoBehaviour
{
//Attempt at making the ammoGiven variable public
//public int AmmoController.PickUpAmmo(Ammo);
public int ammoGiven;
public int minAmmo;
public int maxAmmo;
public bool pickedUp;
public UnityEvent interactAction;
void Update()
{
}
public void PickUpAmmo()
{
pickedUp = true;
if (pickedUp = true)
{
ammoGiven = Range(minAmmo, maxAmmo);
Debug.Log(ammoGiven);
Debug.Log(NewAmmoGiven);
}
Destroy(gameObject);
}
}
In the pistol shoot script I am trying to call the variable ammoGiven in order to add it to the currentAmmo variable in my pistol script but this is not working. The script thinks that ammoGiven is equal to 0 but I have no lines of code that make this the case.
Below is my attempt at calling the ammoGiven variable in the pistol shoot script.
public static AmmoController ammoControllerReference;
public int AmmoGiven = ammoControllerReference.ammoGiven;
I have tried to make the ammoGiven variable public and I have tried to call it in the pistol shoot script but I either get an error or I am given the wrong value when I use it in the pistol shoot script
The problem is in the PickUpAmmo()
function. It is destroying the gameObject right after initializing the ammoGiven
variable.
What you can do is have ammo variable in the shoot script and then assign the variable to it from the AmmoController
. This way, the value will not be lost upon destroying the gameObject.
You can also try creating a static script that holds all the game related values like this:
public static class GameValues {
public static int Ammo = 0;
}
When you pick up the ammo, you can assign the value:
GameValues.Ammo = Range(minAmmo, maxAmmo);
and when you want to access the ammo:
Debug.Log(GameValues.Ammo);