- Home /
How to add a Script to a GameObject during Runtime [2016]
I try to search for this but most of methods out there (Google, other questions, etc[...]) aren't properly updated, because they use ways now deprecated to do this and the last version of the editor which is what i'm using right now (to this day, 01-02-2016, version 5.3.1) is not accepting them like valid ones or updating them like it should.
I saw on the internet too, in the official tutorials something about doing through generic methods, but i don't have any idea how to make it work out and i'm pretty much a newbie in C#.
Could you please show me one example of how to use generics to insert an specific script through (i suspect) addComponent to a GameObject?
Just for the sake of argument, i'm adding the script where i'm trying to set this to work, take in consideration than (in this case) is an object than generate objects:
using UnityEngine;
using System.Collections;
public class Controller : MonoBehaviour {
// Use this for initialization
void Awake () {
Vector3 vecAwake = new Vector3 (1, 1, 0);
GameObject BuildModeController = new GameObject ();
this.addBuilder (BuildModeController, vecAwake);
}
void addBuilder(GameObject go, Vector3 vecAwake){
go.transform.SetParent (this.transform, true);
go.transform.position = vecAwake;
Debug.Log (go.name);
//This doesn't work
go.AddComponent<ScriptableObject> (go.name+".cs");
// i also trying adding this, and using it through string
//(method also by today, deprecated):
//"Assets/Scripts/Controllers/Controller.cs (23,3)", ");
}
}
Thanks in advance
PS: Feel free to ask or request any kind of clarification or comment than help to improve quality of this question too.
http://answers.unity3d.com/questions/471531/add-component-script.html duplicate, one of many duplicates of this exact question, actually. The reference on GameObject will have AddComponent() too. This used to be in the scripting guide, probably moved it over to the tutorial section though, haven't checked
Answer by felixfors · Feb 08, 2016 at 09:11 PM
public GameObject test;
void Start()
{
test.AddComponent<ScriptName>();
}
Answer by IssataySC · Jun 01 at 03:56 AM
If your script lies within certain namespace, you should follow the following format
GameObject.AddComponent(typeof(namespace.className))`;