Using System.Serializable

Basically, I am playing around with System.Serializable just to get a grasp of it.

I’ve got the following code in one script…

[System.Serializable]
public class theGunList {

	public string gunName;
	public int currentAmmo;
	public int currentCartridge;

	public static string _gunName;
	public static int _currentAmmo;
	public static int _currentCartridge;
	public int maxAmmo;
	public int maxCartridge;
	public GameObject projectilePrefab;

	void Awake()
	{
		// Make the static variables have the names of the guns in the elemnt.
		_gunName = gunName;
		_currentAmmo = currentAmmo;
		_currentCartridge = currentCartridge;
	}

}

Now, I’m attempting to make it so I can see details and adjust variables of each gun in the inspector, but also try and be able to access those details in another script. That other script being “PlayerGUI.cs”

Unfortunately, no errors come up, just no information or any details are displayed.

This is PlayerGUI.cs

	public theGunList[] instance;
	public List<theGunList> gunListName;

	void Awake()
	{

	}

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	void OnGUI()
	{
		GUI.Label (new Rect (Screen.width / 2, Screen.height / 2, 100, 50), "Gun" + theGunList._gunName);
	}

This would work, however you never called any Awake method in your theGunList classes. Awake is a message sent to MonoBehaviour classes. Serializable custom classes are just classes where the public (non static) serializable members are serialized with the MonoBehaviour that contains the instance.

What’s the point of having two different arrays / collections of that class? When using the inspector it’s irrelevant if you use a List or an array, you have both, why?

And again you never call Awake on any of your instances which might be inside the “instance” array or the “gunListName” List to actually copy your instance variables to the static variables. In order to be able to call Awake it should be a public method. And if it’s ment to set that weapon active you might want to rename it to “Select()” or something.

Anyways if you just want to have one active weapon at a time you might want to use a static variable of your “theGunList” class (which btw has a horrible name)

[System.Serializable]
public class Gun
{
    public static Gun current = null;
    public string gunName;
    public int currentAmmo;
    public int currentCartridge;
    public int maxAmmo;
    public int maxCartridge;
    public GameObject projectilePrefab;
    public void Select()
    {
        current = this;
    }
}

So to make the 2nd gun the current gun just do:

// in your monoBehaviour
public List<Gun> gunList;

void Awake()
{
    gunList[1].Select();
}

void OnGUI()
{
    GUI.Label (new Rect (Screen.width / 2, Screen.height / 2, 100, 50), "Gun" + theGunList.current.gunName);
}