Asimm Asimm - 1 month ago 4x
C# Question

Set values to component script before attaching it to a gameObject

I'm creating crowd control effects (slow,freeze,stun,snare...) they are all in separate scripts and they are being attached to the player's gameObject when needed. However in case i want to have 2 slows at a time with different values in the script i'm not sure how i can change those. I want to be able to sort of instantiate the script class before adding it to the actual gameObject.

Foo someClass = new Foo();
someClass.Duration = 10;
someClass.SlowAmount = 10;

Foo someClass2 = new Foo();
someClass2.Duration = 1;
someClass2.SlowAmount = 1;


Firstly I suggest always using uppercase for your classes and lowercase for variables to easily distinguish them:

SomeClass, SomeClass2

To answer your question, you could save the class in a variable and then manipulate the values:

SomeClass someClass = playerObject.AddComponent<SomeClass>() as SomeClass;
someClass.duration = 10;
someClass.slowAmount = 10;