- Home /
MonoBehaviour inheritance problem
I came across a dilema that I judge to be very simple, but I can't figure it out, so let's say we have this:
//Gun.cs
using UnityEngine;
class Gun : MonoBehaviour
{
void Start()
{
print("Print Gun");
}
}
//Rifle.cs
using UnityEngine;
class Rifle : Gun
{
void Start()
{
print("Print Rifle");
}
}
I would like to drag the Rifle.cs script into a game object, press run, and have both prints appear on my console.
Is there any way to achieve that? without having to write some code in all my classes that derive from Gun?
Answer by brunocoimbra · Jun 27, 2016 at 01:55 AM
To modify and still have access to inherited methods, you need to use "virtual" and "override" in your methods.
//Gun.cs
using UnityEngine;
class Gun : MonoBehaviour
{
protected virtual void Start()
{
print("Print Gun");
}
}
//Rifle.cs
using UnityEngine;
class Rifle : Gun
{
protected override void Start()
{
base.Start();
print("Print Rifle");
}
}
The virtual keyword tells "that method can be changed", the override keyword tells "I am going to change that one", then the base gave you access to your parents unchanged methods.
I thought about that, but as I said I would like to do it in a way that I don't have to write code in all my derived classes. I have to write base.Start() on every class that inherits from Gun. But looking at it again, its not much of a big deal I think.
One thing you could do would be something like that:
//Gun.cs
using UnityEngine;
class Gun : $$anonymous$$onoBehaviour
{
void Start()
{
print("Print Gun");
Initialize();
}
protected virtual void Initialize()
{
// leave it empty
}
}
//Rifle.cs
using UnityEngine;
class Rifle : Gun
{
protected override void Initialize()
{
print("Print Rifle");
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612083733im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Using AddComponent to add a Sub Class using a String 4 Answers
C# Inheritance, base class attributes, override and null object 1 Answer
How to serialize fields for both base and derived classes? 0 Answers
An OS design issue: File types associated with their appropriate programs 1 Answer
Assigning Serializable child class, not visible in Editor 1 Answer