Getting component from derived classes
Hello there !
I'm still new at the unity coding but I do know how to workaround with c# but I'm having doubts in what to do with my aproach. So the idea is to have the abstract class Habilities and three derived classes: HabilitiesAttack, HabilitiesDefense, HabilitiesRogue. Each derived class will be in a canvas and each canvas will represent an individual tech tree. The access to this three canvas will be by buttons through OnClick using a dedicated function that sets active the screen to be opened and deactivates the current one. This is all done in the canvas habilities menu which has this method:
void Awake() => Init();
private void Init()
{
previousScreen = GameObject.Find(previousScreenName);
/*attack = new HabilitiesAttack(gameObject.name, dbManager.GetAttackPoints());
defense = new HabilitiesDefense(gameObject.name, dbManager.GetDefensePoints());
rogue = new HabilitiesRogue(gameObject.name, dbManager.GetRoguePoints());*/
//attack = gameObject.AddComponent<HabilitiesAttack>();
attack = GameObject.Find("Canvas_HabilitiesAttack").AddComponent<HabilitiesAttack>();
attack.FillSettingsData(gameObject.name, 100);
defense = gameObject.AddComponent<HabilitiesDefense>();
defense.FillSettingsData(gameObject.name, 100);
rogue = gameObject.AddComponent<HabilitiesRogue>();
rogue.FillSettingsData(gameObject.name, 100);
Debug.Log(attack.gameObject.name);
}
The problem is when I try to debug log the name or even use the button to change the screens it will give me: NullReferenceException: Object reference not set to an instance of an object HabilitiesMenu.Init () (at Assets/Scripts/HabilitiesMenu.cs:25) ----> Canvas_HabilitiesAttack HabilitiesMenu.Awake () (at Assets/Scripts/HabilitiesMenu.cs:15)
But if I have the Canvas_HabilitiesAttack active right from the start it will work. Isnt the Awake beingcalled because of the canvas not being activated? What do you recommend that I would do? Also I m putting the scripts in the canvas itself and using the canvas itself to the object on the OnClick buttons as it show on the following pictures.
GameObject.Find won't return any disabled gameObjects. I would just stay away from using it ever - as it has perf issues.
Can you not just reference the GameObject straight away on the script thats trying to find it?
I m not sure what to do. I had an approach but I think that is necessary to make the abstract class and derived classes being apart from all the canvas. I think I should have a controller for each canvas that should use an instance of the respective derived class. What do you think? BTW how should I reference the gameobject?