Addcomponent() with parameters in Unity3d?

Asked

Viewed 108 times

1

Good morning, everyone!

In short, 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 the use of "Addcomponent()", but I am needing that when creating a new object, 3 parameters are passed. I tried to use the method itself called "Addcomponent("So-and-so", "Fire", 1)", but it didn’t work.

Someone could explain to me how to pass "parameters" in the Addcomponent?

1 answer

2


You must add the component to the object you want and then call a method/function to assign/define 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 ( 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 taken 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 haven’t worked with Unity for a while, but I think the process will continue. I would go with the first option, but that will now depend on your need.

  • 1

    Exactly. I just wanted to comment that the method AddComponent already returns an instance of the component Fulano created/added to the game Object, so you can do it directly objecto.AddComponent<Fulano>().init("Fire", 1);. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.