This is a newbie question, but I really don’t get how class constructors work.
I created a class, say “MyClass”, and want to create a new object in another class, say “MyGame”, and instantiate it with “MyClass”. I code in C# and used the old “new MyClass(parameters)” constructor.
However, this is not allowed in Unity. I tried removing the “MonoBehaviour” inheritance from both classes, but it did not solve anything.
Besides, after reading the documentation, I tried creating a GameObject and using its AddComponent() method. However, I can’t understand where I should pass the parameters to my constructor, and whether I should change the code inside “MyClass”.
Custom component, aka MonoBehaviour derived objects, can’t have parameters in it’s constructor and can’t be created manually with new. Components are part of the strategy-design-pattern and can only be created with AddComponent()
For usual classes (not derived from MonoBehaviour) there’s no problem creating them the usual way with new.
class MyClass
{
public string name;
public MyClass(string aName)
{
name = aName;
}
}
MyClass mc = new MyClass("FooBar");
You cant use constructors with mono behaviors but you can get something similar like this by attaching a similar script to your prefab.
public class InventoryItem : MonoBehaviour
{
public ItemDataClass ItemData;
void Start()
{
GetComponent<Image>().sprite = ItemDataParam.ItemIcon;
}
}
And when you instantiate the object from another script change its ItemData variable after you instantiate it. That way you instantiate the prefab in the editor and also from a script.
it is more the template method pattern http://en.wikipedia.org/wiki/Template_method_pattern since unluckily the Unity3D framework does not even know what an interface is
– sebas77