- Home /
How to select a class instance from the inspector?
In my game I would like to implement an universal ammo and weapon system that would be usable for any kind of weapon. So I declared an ammo class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Ammo {
public int MaxAmmo;
public int CurrentAmmo;
public Ammo(int maxAmmo)
{
MaxAmmo = maxAmmo;
}
public void MaxOutType()
{
CurrentAmmo = MaxAmmo;
}
public void GetAmmo(int amount)
{
CurrentAmmo += amount;
}
public void UseAmmo(int numOf)
{
CurrentAmmo -= numOf;
}
}
Than I created a script to hold diferent Ammo types:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AmmoSystem : MonoBehaviour
{
[SerializeField]
public Ammo Basic = new Ammo(200);
public Ammo Rockets = new Ammo(50);
public Ammo AirRockets = new Ammo(75);
public Ammo Cells = new Ammo(150);
}
To organize my project I decided to make two weapon script one for nonphysical(Raycast) projectiles called RaycastingWeapon and an another for physical ones(like a rocket launcher) called: PhysicalProjectileWeapon
My plan was to create unique weapons using these two script from the inspector.
These would use different kind of ammo but would share the same script with diferent properties. The essential here is that I would like to be able to select an ammo type from the inspector using a dropdown menu for exapmle.
Is it possible somehow or are there a better way of doing that ?
I know that this is maybe not the best title for this question, sorry about it.
Thanks in advance.
Answer by Woltus · Jul 03, 2017 at 02:02 PM
You can use enum, e.g.:
public class AmmoSystem : MonoBehaviour
{
[SerializeField]
public Ammo Basic = new Ammo(200);
public Ammo Rockets = new Ammo(50);
public Ammo AirRockets = new Ammo(75);
public Ammo Cells = new Ammo(150);
public enum AmmoTypes { basic, rockets, airRockets, cells }
}
Then in your weapon script you can use:
public AmmoSystem.AmmoTypes ammoType = AmmoSystem.AmmoType.basic;
and in weapon inspector You will have a dropdown list with all ammo types.