- Home /
Passing arguments to base constructor fails
I have a Character class with a ragdoll and a HumanoidCharacter subclass that should set it.
public class Character : MonoBehaviour {
private Ragdoll ragdoll;
public Character(Ragdoll ragdoll, int maxInventorySize) {
if (ragdoll == null) throw new System.ArgumentNullException("ragdoll");
this.ragdoll = ragdoll;
}
}
public class HumanoidCharacter : Character {
public HumanoidCharacter(int maxInventorySize) : base(new Ragdoll(new ItemSlot[] {new ItemSlot(ItemSlotType.RightHand)}), maxInventorySize) {
}
}
public class PlayerCharacter : HumanoidCharacter {
public PlayerCharacter() : base(32) {
}
}
I'm getting the ArgumentNullException for ragdoll when I attach PlayerCharacter to a GameObject.
I would have thought that PlayerCharacter's constructor is called, which calls HumanoidCharacter's sonstructor which then calls Character's constructor with the new Ragdoll. What's going wrong?
This is an interesting question. Good you've fould already the solution ;)
The problem with the constructor is that it is called whenever you usually don't expect it. Everytime you save / load a scene in Unity or a script gets (re-)compiled, Unity recreates the objects and deserialize the serialized members to restore the "old state".
I don't see a direct reason why this setup shouldn't work.
What's the base class of Ragdoll? I guess it's a "usual" class derived from System.object? $$anonymous$$eep in $$anonymous$$d that you can't create $$anonymous$$onoBehaviours with "new" since it's part of the strategy-pattern. Components can only live on GameObjects and can only be added with AddComponent.
Wait, maybe it it really was a $$anonymous$$onoBehavior. It isn't right now, but maybe I changed that while I hunted down the error and already forgot. It kind of resonates with some dark part of my memories, that got buried while I was working too late.
Answer by tneshi · Feb 22, 2012 at 03:35 PM
I have in the mean time read, that using Constructors for MonoBehavior is generally discouraged. I changed my code to set those variables in Awake instead. Now it works.