Passing values into base constructor with MonoBehaviours

So I’m writing my own container classes for GUI labels, buttons, etc to make my life a lot easier. I have a container class for a button which has a base constructor of…

 public PsyUI_Button(float xPos, float yPos, float width, float height, string text)
{
    this.xPos = xPos;
    this.yPos = yPos;
    this.width = width;
    this.height = height;
    this.text = text;
}

This is all fine and dandy but, of course, it appears that I can only pass values to the base constructor by using the ‘new’ keyword.

But because my classes derive from MonoBehaviours, the compiler will throw up the error, “You are trying to create a MonoBehaviour using the ‘new’ keyword. This is not allowed”.

So how do I instantiate an object derived from MonoBehaviours and pass in values for the base constructor at the same time?

I don’t want store the object into a variable and manually change the values line by line because that would lead to a silly amount of lines once I instantiate lots of objects. :\

promoting my related question: http://answers.unity3d.com/questions/445444/add-component-in-one-line-with-parameters.html

1 Answer

1

You could use a factory method:

public class MyGUI : MonoBehaviour {
      private static GameObject guiObj;
      public static GameObject GUIObj {
           get {
                if( guiObject == null) {
                      guiObject = new GameObject("GUI Object");
                }
                return guiObject;
            }
      }

      public static MyGUI CreateMyGUI( float xPos, float yPos, float width, float height, string text) {
            var thisObj = GUIObject.AddComponent<MyGUI>();
            //calls Start() on the object and initializes it.
            thisObj.xPos = xPos;
            thisObj.yPos = yPos;
            thisObj.width = width;
            thisObj.height = height;
            thisObj.text = text;

            return thisObj;
       }
}

then call it as such:

MyGUI someButton = MyGUI.CreateMyGUI( 0 , 150, 240, 75, "Some Text");

Normally you could add a private constructor as well so that you can’t instance the class from another class, but Monobehaviour won’t let you instance it through a constructor anyway so it doesn’t really matter.