AddComponent () with parameters in Unity3D?

1

Good morning everyone!

In summary, I am trying to use "new" to build an object in Unity, but it says that it is not recommended to use new to instantiate an object and suggests using "AddComponent ()" but I am when creating a new object, 3 parameters are passed. I tried to use the method's own "AddComponent (" So-and-so "," Fire ", 1)", but it did not work.

Would anyone know how to explain how I pass "parameters" in AddComponent?

    
asked by anonymous 21.11.2017 / 12:56

1 answer

2

You should add the component to the object you want and then call a method / function to assign / set the values of that new component.

Example:

// a class fulano deverá ter uma funcao init

objecto.AddComponent<Fulano>();
objecto.GetComponent<Fulano>().init("Fire", 1);

You can also reference everything in a line (a suggestion given by Comrade Luiz Veira):

objecto.AddComponent<Fulano>().init("Fire", 1);

If you really need to create the object with a constructor, see the example below from answers.unity.com

 public class Foo : MonoBehavior {    
    public static Foo MakeFooObject() {
       GameObject go = new GameObject("FooInstance");
       Foo ret = go.AddComponent<Foo>();
       // do constructory type stuff here, you can add parameters if you want but you're manipulating the instance of Foo from the line above.
    return ret;
    } 
 }

I have not worked with Unity for some time now but I think the process stays the same. I would opt for the first option, but this will now depend on your need.

    
21.11.2017 / 13:18