- Home /
Create an object and assign code to it via script?
I was wondering how it would be possible to create an instance of a prefab and assign a character controller and scripts to it by a code file (preferably in javascript). In my case, the prefab is named Smiley4, and there are two scripts that need to be placed on it when it is instantiated.
thanks in advance, 2Tie
Edit: Mah, i should probably add my current code for it: var NewModel : GameObject; var P1Charname:String = "Smiley4";
function Start() { Instantiate(NewModel, transform.position, transform.rotation); GameObject.Find(P1Charname+"(clone)").AddComponent(CharacterController); GameObject.Find(P1Charname+"(clone)").AddComponent("Gui_StatDisplay"); GameObject.Find(P1Charname+"(clone)").AddComponent("P1Script"); } Smiley is correctly instantiated, but the scripts aren't added...
could you put all your scripts into one and have that set as standard on the prefab?
Answer by efge · Mar 22, 2011 at 11:54 PM
You could use GameObject.AddComponent
Edit:
Your script could look like this:
var NewModel : GameObject;
function Start() { var clone : GameObject; clone = Instantiate(NewModel, transform.position, transform.rotation); clone.AddComponent("CharacterController"); clone.AddComponent("Gui_StatDisplay"); clone.AddComponent("P1Script"); }
The code I've set up right now goes var New$$anonymous$$odel : GameObject; var P1Charname:String = "Smiley4";
function Start() { Instantiate(New$$anonymous$$odel, transform.position, transform.rotation); GameObject.Find(P1Charname+"(clone)").AddComponent(CharacterController); GameObject.Find(P1Charname+"(clone)").AddComponent("Gui_StatDisplay"); GameObject.Find(P1Charname+"(clone)").AddComponent("P1Script"); } It instantiates the object, but nothing is added.