- Home /
Adding existing script at run-time and changing it's properties
Hello,
I am adding an existing scripts at run-time. Different camera effects scripts. I want to access their properties and set values in code, like fade, Contrast (Some scripts has additional properties).
To add the script to the camera is use the following method:
System.Type MyScriptType = System.Type.GetType(StringOfMyEffectScript + ",Assembly-CSharp");
Component effectInstance = Camera.main.gameObject.AddComponent(MyScriptType);
In design time Unity does not know which properties exists since script is not loaded yet. How do i set script properties at run-time ?
Answer by ShadyProductions · Aug 04, 2017 at 06:50 AM
You can only use AddComponent to add MonoBehaviour to an object.
So if your script is called
Weapon for example, it MUST inherit from MonoBehaviour in order to be able to use AddComponent, you also don't require to get the type.
public class Weapon : MonoBehaviour { public string Name; }
var weaponScript = Camera.main.gameObject.AddComponent<Weapon>();
weaponScript.Name = "blabla";
On a side note, it might be better to already have the scripts on the objects. And instead simply disabled them and when you need to enabled them. AddComponent is an expensive call.
Thanks for the answer, I have like 50 scripts of different camera effects. Here you are defining the script (Weapon) in code, while i am adding an existing script but from inspector i set the string name of the script.
What you are saying that it is not possible to achieve what i want ? $$anonymous$$y Scripts does inherit from $$anonymous$$onoBehaviour .
$$anonymous$$ate, every script is defined in code? lol this was an example. All your exisiting scripts are scripts no?
Just use AddComponent<SCRIPTNA$$anonymous$$E>();
and it will add the script add component will return your script aswel.
Yes, i understand :) Since i have like 50 different script names. i would like to be able to do something like:
string ScriptName="$$anonymous$$yEffectScript1"; AddComponent<ScriptName>();
Your answer
Follow this Question
Related Questions
Unloading Broken Assembly | How to solve this !? 2 Answers
How to make sure than one script affect the player of the specific client, and not the other 2 Answers
The spaceship acceleration script is good ? And how to use it with engine ? 0 Answers
How do I tell my code which window the game runs in? 0 Answers