Hey, I could run a test but thought it would be faster to ask since I am sure someone knows. Will methods like Update(), LateUpdate() execute in the classes that you inherit from?
Example, lets say I have a class called weaponB that inherits from weaponA class that has basic variables like hit points, magic and so on, and weaponA class inherits from the base class MonoDevelop. Can all the classes that inherit from weaponA (weaponB for example) use the update() method in weaponA? Can I just write the code once in the weaponA class and have all classes that inherit from weaponA use the update() method?
Currently I have a camera that follows the different weapons around the screen and they all have the same redundant code to perform the identical camera task. I was hoping to make a class that they could all inherit from to lighten the syntax.
Hi, it is the simplest lesson in OOP or Inheritance, you just need to use Virtual or Abstract keyword on base class on Update method, then use Override keyword on sub class.
Abstract mode:
public abstract class Weapon : MonoBehaviour {
protected abstract void Update ();
}
public class WeaponA : Weapon {
protected override void Update () {
// Do your stuff here
}
}
Virtual mode:
public class Weapon : MonoBehaviour {
protected virtual void Update () {
// Do your base stuff here
}
}
public class WeaponA : Weapon {
protected override void Update () {
// base.Update();
// You can call base.Update () here to call the base class update method or you can ignore it and do your stuff
}
}
Thank you, I will read the docs on that. What [Antony-Blackett]( https://discussions.unity.com/t/691210 members/antony-blackett.35561/) mentioned is what I initially was thinking. I was unaware of this approach.
This does only apply if you do not override methods, but let them “co-exist” as seperate methods.
Unless these are private, you’ll then get a warning which suggest you to hide the member instead with the usage of the “new” keyword, which is usually not desired and should be avoided.