- Home /
Abstract Class - Monobehaviour Functions
So I have a bit of a dilemma.
I want to use an inheritance structure for guns in my game. I want to make guns an abstract class and then have types of guns (lasers, rifles, shotguns) which inherit from it and then create specific instances of these weapons. At the moment I'm doing this as an abstract class because I want to be able to create instances of guns and add them to a list. I don't want them to exist as external MonoBehaviour scripts because I want to be able to have a list of weapons in the players inventory / storage and don't want an instance of each MonoBehaviour on the GameObject. I am doing so thusly:
ActiveWeapon = new Rifle("Starter Gun", 30, 5, 0.3f, 2.0f, 100.0f, true, 3.0f);
The issue I'm encountering is that I want to be able to utilise some of the methods which are derivative of MonoBehaviours for example :
public override void Shoot ()
{
if (CanShoot)
{
StartCoroutine(Cooldown());
Rigidbody bullet = Rigidbody.Instantiate(BulletPrefab, transform.position, transform.rotation);
... // Addforce etc.
...
}
}
public IEnumerator Cooldown()
{
CanShoot = false;
yield return new WaitForSeconds (FireRate);
CanShoot = true;
}
Obviously since this isn't a MonoBehaviour class I can't use functions such as Instantiate to create bullets or WaitForSeconds to stagger them.
The issue is that most of these functions and references are specific to MonoBehaviours. However my guns will be attached to a MonoBehaviour (PlayerResources.cs). How should I tackle this issue?
Hi. Imho PlayerResources could for example expose static Instantiate wrapper method PlayerResources.Instantiate(prefab,position,rotation). Not even to mention that bullet should be handled by some kind of pooling manager and not Object.Instantiate. Also you can think about replacing Cooldown method with, like, canShoot property maybe:
private float lastShotTime = 0f;
private float cooldownTime = 1f;
public bool canShoot {get{return Time.time>lastShotTime+cooldownTime ? true : false;}}