- Home /
Script spawns another script within the gameobject
Is it possible to have a script spawn another script in the same gameObject? I attempted to do so with Instantiate, but it came up with an error.
Answer by iwaldrop · Jun 23, 2013 at 06:51 PM
To create a new instance of a regular class you use the new keyword. The Instantiate method just creates new instances of game objects from originals (like prefabs or existing game objects). Here's two example for instantiating new classes using C#. The second allows you to initialize script variables without constructors.
Foo foo = new Foo();
Bar bar = new Bar
{
someVar = someValue,
otherVar = otherValue
};
Answer by fafase · Jun 24, 2013 at 06:40 AM
If the class you are trying to instantiate inherits from mono behaviour, then your class is turned into a component. Then you can add a class/component using AddComponent:
ScriptName script = gameObject.AddComponent<ScriptName>();
script.publicMember = value;
The method returns a reference to the script attached, you can then modify it.
The other way is to create using the usual C# way if your script does not inherits from MonoBehaviour (if it does this method will return an error):
ScriptName script = new ScriptName();
script.publicMember = value;
Your answer
Follow this Question
Related Questions
Checking if a position is occupied in 2D? 1 Answer
Help touch button 1 Answer
Check if with a spawned gameobject 1 Answer
Destroy all GameObjects EXCEPT some... 2 Answers