Trouble with inheritance
Hi guys. I am having a really annoying problem with inheritance. I am using UI to dynamically populate a shop with Weapons from a list.
Weapon is the base class and I then have other classes such as Pistol, Machinegun, etc, that extend Weapon.
public abstract class Weapon : MonoBehaviour{
public int weaponID;
}
...
public class Pistol : Weapon {
public Pistol() {
weaponID = 1; // test value;
}
...
public class MachineGun : Weapon {
public MachineGun () {
weaponID = 2; // test value;
}
...
for (int i = 0; i < weaponsForSale.Length; i++) {
GameObject weaponPrefab = Instantiate (weaponsForSale [i]);
Weapon weaponComp = weaponPrefab.GetComponent<Weapon>();
Debug.Log(weaponComp); // this displays the correct class, Pistol, Machinegun, etc
Debug.Log(weaponComp.weaponID); // this displays 0, the base stat of weapon instead of the pistol, machinegun, etc
Answer by spraw · Nov 14, 2016 at 06:04 AM
You cannot/shouldn't call a constructor in Unity like that. Instead call Awake, Start, etc.
public class Pistol : Weapon {
void Start() {
weaponID = 1; // test value;
}
}
https://unity3d.com/learn/tutorials/topics/scripting/classes
Don't you need to override values set in base classes? Don't they have to be virtual?
Your answer
![](https://koobas.hobune.stream/wayback/20220612100634im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Not sure how to make my classes interact in the way I intend them to 1 Answer
Child class cannot access property in method? 1 Answer
How do I assign ascending numbers to a group of the same objects 1 Answer
Resetting Camera Position 1 Answer
Easy question: X axis overriding Y. Please help! :D 0 Answers