Forum Archive › Am I using classes correctly? › Reply To: Am I using classes correctly?
@eithman Inheritance in this case is not needed, but I will show you how you can use it nonetheless. For the cannon script, it’s inheriting from the Weapon class. All the public methods within the base class will be available to the children than inherit from it.
Everything looks setup properly in the base class, albeit I’m not familiar with the Oculus inputs. So the child class, Cannon, inherits the Weapon class so everything public should be made available. We don’t need to create a new class for this.
In the weapon class if you want to call the BulletDelay or ShootGun methods you’d call them directly as you would in the Weapon class. I didn’t make that clear initially so I’ll provide a code snippet:
//this is in the Cannon script
void Update() {
BulletDelay();
}
Since the Cannon class is inheriting from the Weapon class, you also need to assign any components needed like the audio source. The Cannon class would need an AudioSource component that you need to assign. If it’s public (which it is) you can manually assign it, otherwise use GetComponent to grab it for you automatically.
To add onto that you can also override methods. So if you wanted all weapons to have the same general mechanics, but use them in different ways you’d override specific methods to work in a different way. You’d use a virtual method in the base class, allowing child classes to override those methods. Here is a very simple example:
public class Weapon : MonoBehaviour {
public AudioSource aud;
public bool canFire;
public virtual void ShootGun () //making it virtual allows you to override it within a child class
{
if(Input.GetButtonDown("Fire1")){
Debug.Log("Pew Pew");
}
}
}
public class Shotgun : Weapon { void Update () { ShootGun(); }//use override instead of virtual to modify the methodpublic override void ShootGun() { if(Input.GetButtonDown("Fire2")) Debug.Log("Bang Bang"); } }
There’s a lot more to it as well, but those are basic examples. You could also do chain inheritance. So the Shotgun class may also have it’s own child classes. Those child classes would have access to all the public methods and variables available to the shotgun class as well.