Answer the question
In order to leave comments, you need to log in
How to change variables in another class?
I have a weapon script, there are variables there: Ammo, ExtraAmmo, ClipAmmo. They are responsible for the number of cartridges in the clip, additional cartridges and the maximum number of cartridges in the clip. There is a FireData method where it is checked if the cartridge in the clip is 0, then start reloading, but I can’t write how the weapon should be reloaded, because I don’t know what number in these three variables. I entered them as parameters, but how do I call this in Invoke? Is there a better way?
using UnityEngine;
public class Pistol : MonoBehaviour
{
public int Ammo;
public int ExtraAmmo;
public int ClipAmmo;
public float RateOfFire;
public float ReloadTime;
public float Damage;
[Space]
public bool CanFire;
public void Update()
{
if(Input.GetButtonDown("Fire"))
{
Fire();
FireData();
}
}
public void Fire()
{
}
public void FireData()
{
Ammo--;
if(Ammo == 0 && ExtraAmmo != 0)
{
GunManager.StatsUI.text = "Reloading...";
Invoke(GunManager.Reloading(ref Ammo,ref ExtraAmmo,ref ClipAmmo), ReloadTime); // Нужно string,а у меня void
}
else
{
GunManager.StatsUI.text = "You dont\nhave ammo.";
}
}
}
using UnityEngine;
using UnityEngine.UI;
public static class GunManager
{
public static Text StatsUI;
public static GameObject FirstGun;
public static GameObject SecondGun;
public static void Reloading(ref int Ammo, ref int ExtraAmmo, ref int ClipAmmo)
{
if(ClipAmmo <= ExtraAmmo)
{
ExtraAmmo -= ClipAmmo;
Ammo = ClipAmmo;
}else
{
Ammo = ExtraAmmo;
ExtraAmmo = 0;
}
}
}
Answer the question
In order to leave comments, you need to log in
1. Not a variable, but a field.
2. To access them, you need to take an instance of this class.
It seems that the unit has some components that can be obtained via GetComponent
I would make variables that need to be changed from another class static (public static ammo;). And in another class I would do this
// Что-то до этого
Pistol.ammo = 7; // название скрипта, в котором находится переменная; точка; название СТАТИЧЕСКОЙ переменной; равно; нужное число;.
// Что-то после этого...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question