Search code examples
c#unity-game-engineunity-components

Unity3d AddComponent taking variable


Details: In C# on Unity3d Searched on the unity documentation but the example doesn't fit to my case, same for other websites i visited. (i did not list them as i should.)

What i am trying to do is passing a class variable with a constructor to be a component:

CustomComponentClass ccc = new CustomComponentClass(2343, "blop");
gameObject.AddComponent(ccc);

I want to know if what i am trying shoud work, or if i missed something...

Problem:

gameObject.AddComponent(ccc); -> cannot convert ccc to string.

gameObject.AddComponent<ccc>(); -> Are you missing a using directive or an assembly reference? (i'm not, i'm using a variable and all is in the same namespace)

gameObject.AddComponent<CustomComponentClass>(ccc); -> UnityEngine.GameObject.AddComponent(string) cannot be used with the type arguments

gameObject.AddComponent<CustomComponentClass>(2343, "blop"); -> No overload for method AddComponent takes 2 arguments

Whatever i try doesn't work. C# is not really like javascript, if i'm right we used to be able to pass variables in the addcomponent in js.

Context: I must absolutely pass it in the constructor. I have 2 fields that are private, and i can't affort it tobe static, constants, or public for safety reason.

Options: If the answer is too complicated for me i will probably make get/set and check if the fields are empty.


Solution

  • You absolutely do not need to pass it in to the constructor.

    Instead create the component as normal (without parameters), add the component to the gameobject, then call a setup method on the component that provides the necessary parameters and runs whatever code you currently have in the constructor.