- Home /
Instantiate a class that takes an overload?
Hello all!
I have a class called HeroUnit that takes a BattleManager as an argument. In the BattleManager class, I am instantiating Heros from an array, however, I cant seem to figure out where to pass it a battlemanager object. I want to pass it the battlemanager object that its currently being instatiated from with 'this'. The weird part is that this code creates the Gameobjects that have the HeroUnit script on it just fine and VisualStudio doesnt complain about them not taking a BattleManager as an argument. Any help would be MUCH appreciated! Here is an example:
public class HeroUnit : Unit
{
BattleManager battlemanager;
public HeroUnit(BattleManager newBattleManager)
{
battlemanager = newBattleManager;
}
}
public class BattleManager
{
public HeroUnit playerUnit;
public void BattleSetup()
{
Debug.Log("Creating Units now!");
// Create Heros at their spawn points and store them into variables.
CreateHeroes();
// Access the HeroUnit information on the Hero GameObjects and store them into variables.
playerUnit = createdHeroes[0].GetComponent<HeroUnit>();
}
void CreateHeroes()
{
if(party.currentParty.Count <= 3)
{
createdHeroes = new GameObject[party.currentParty.Count];
for (int i = 0; i < party.currentParty.Count; i++)
{
createdHeroes[i] = Instantiate(party.currentParty[i], heroLocations[i]);
}
}
}
}
Answer by xxmariofer · Jul 31, 2020 at 08:06 AM
if the HeroUnit is attached to the gameobject it means thaat unit derives from monobehaviour and if thats the case you cant use constructors, they get called multiple times when the gameobjects get serialize/deserialize, just avoid it and create an init method
public class HeroUnit : Unit
{
BattleManager battlemanager
public void Init(BattleManager newBattleManager)
{
battlemanager = newBattleManager;
}
}
and when instantiate
for (int i = 0; i < party.currentParty.Count; i++)
{
createdHeroes[i] = Instantiate(party.currentParty[i], heroLocations[i]);
createHeroes[i].GetComponent<HeroUnit >().Init(this);
}
Thanks for the response man!
I'm not familiar with Init methods. I tried looking into it a good bit. It looks like they essentially work the same way as a constructor would?
I tried implementing it the way you did and was unsuccessful... Unity doesn't seem to recognize the word Init as a reserved term. It's kinda treating it like a generic method and asking for a return type. Any idea? Thanks again!
i completly missed, i am talking about Init as a generic method i simply forgot to add the return type
Hmm maybe I am misunderstanding?
When I attempt to get the HeroUnit component on my created Hero Gameobjects, I do it this way:
playerUnit[i] = createdHeroes[i].GetComponent<HeroUnit>();
However, when I add the Init Function like this:
playerUnit = createdHeroes[0].GetComponent<HeroUnit>().Init(this);
It complains about not being able to convert Void into HeroUnit.
feeling pretty confused on this...