Search Unity

Add component to 3D object with parameters to constructor?

Discussion in 'Getting Started' started by MikeTeavee, Jun 19, 2015.

  1. MikeTeavee

    MikeTeavee

    Joined:
    May 22, 2015
    Posts:
    194
    So I want to attach a "Monster" component to a basic 3D cube. I also wanted to pass the parameters to a constructor in Monsters that sets health to a private int called "hitPoints".

    I couldn't get the constructor to work in line #2 of this code, so I made a setter-function in Monster instead, and it works.

    Is there anyway to pass parameters to a constructor in Monster? Or am I forced to do it this way?

    ---
    Here's my code (which compiles and works) ...

    Code (CSharp):
    1. GameObject box = GameObject.CreatePrimitive(PrimitiveType.Cube);
    2. box.AddComponent(typeof(Monster));
    3. box.AddComponent<Monster>().SetHealth(10);
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    No, there is no safe way to use constructors with a MonoBehaviour. The way you've done it is close to correct, except that of course you've added two Monster components, and only set the health on the second one.
     
    Kiwasi, zombiegorilla and jhocking like this.
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    @JoeStrout is right, you can't directly use a constructor with a monobehavior.

    There are two methods I've seen to fake a constructor.

    You can use a factory pattern, where you add a static method to the MonoBehaviour that takes the target GameObject as a parameter, as well as your construction parameters. It then takes care of adding the component and doing initialisation.

    The other is to use the MonoBehaviour only as a thin layer between your GameObject and your actual code. You can then create a regular class with a constructor that the MonoBehaviour references. You will need to pass through the appropriate callbacks as well.
     
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Oh, and for parameter less constructors the Unity way is to use Awake and Start. You can also set parameters immediately after instantiate and then use their values in Start (but not Awake).
     
    MikeTeavee likes this.