I’ve got a basic BuildingController with a BuildingModel variable in it:
using UnityEngine;
using System.Collections;
public class BuildingController : MonoBehaviour {
private BuildingModel model;
private void Awake () {
this.model = this.GetComponentInChildren<BuildingModel>();
}
.
.
.
Now I derived a Tower from the building class:
using UnityEngine;
using System.Collections;
public class TowerController : BuildingController {
private TowerModel model;
.
.
.
The Tower Model Class derives from the BuildingModel Class.
Now I want the TowerController to search its model on the object, but it cannot find it because the component is a “TowerModel” not a “BuildingModel”
Hey,
okay. That was my fault. But even with protected model. The problem is, the “model” variable of the building controller is a “Building Model” and the “model” variable of the “TowerController” should be a “TowerModel”, derived from the building model.
Is there any way to write it in a way, that the Tower Controller uses his Building Controller awake to search for the TowerModel, because it derives from the Building Model?
Your issue lies in the fact that Awake is attempting to assign a generic BuildingModel to a more specific TowerModel.
You could override the Awake Method in TowerController to be:
new void Awake(){
model = this.GetComponentOnChildren<TowerModel>();
}
And this should remove the error, However, there are bigger issues at hand.
You should not be creating new model variables in each child class of BuildingManager (at least, not named model). You are defeating the purpose of inheritance altogether. Additionally, I am not a giant fan of the ‘coupled’ inheritance structure - where BuildingManager has a BuildingModel, TowerManager (a BuildingManager) has a TowerModel (a BuildingModel), etc
I can’t see your exact needs, but I’m willing to bet things could be structured better by just using the normal BuildingModel in TowerController. You can still assign TowerModel as the BuildingModel.