- Home /
Monobehaviour new keyword
Hi,
I'm trying to create a layered behavior system, but seem that monobehaviour can't use the "new keyword"
Here is the code:
void Start () {
GameObject leader = Instantiate(CubePrefab) as GameObject;
Actor leaderActor = leader.GetComponent();
BehaviorBorderAvoid borders = new BehaviorBorderAvoid(0.5f,10);
Behavior wanderer = new BehaviorWander(0.3f,60);
leaderActor.instantiateActor(Color.green);
leaderActor.Speed = 30;
leaderActor.Direction = Actor.GetRandomDirection();
leaderActor.SetPosition(Actor.GetRandomPosition(128,95));
leaderActor.behaviorList.Add(new BehaviorGamepad(0.7f));
leaderActor.behaviorList.Add(wanderer);
leaderActor.behaviorList.Add(borders);
}
behaviorList is always empty! Any solution?
So ins$$anonymous$$d of a construct I can use Start, but still need to figure out a way to pass some values from the Game class to the behavior class. . .
Answer by whydoidoit · Jul 07, 2012 at 01:00 PM
Yes you create new MonoBehaviour derivatives by using AddComponent onto a GameObject.
Seems that add component will not call the constructor. . .as you can see I need to pass some values to the new behavior. . .
You cannot have a parameterised constructor with a $$anonymous$$onoBehaviour - you will need an Initialization method that you call after you have created the instance of the behaviour. Or perhaps you would prefer to have a static function that takes the GameObject that you wish to attach the behaviour to, this could then call your internal function to set the variables, or have direct access itself.
public static void Create$$anonymous$$yComponent(GameObject go, float someParameter)
{
var newInstance = go.AddComponent<$$anonymous$$yComponent>();
newInstance.field = someParameter;
}
Answer by KrankyBoy · Jul 07, 2012 at 10:06 PM
Then use getters and setters (properties). So add the behavior then use properties (basically public vars) to pass the values you need passing OR when Awake or Start is called when the component is added/created then GET the values from elsewhere as needed.