x


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...

more ▼

asked Mar 22 '11 at 11:38 PM

2Tie gravatar image

2Tie
41 5 5 6

could you put all your scripts into one and have that set as standard on the prefab?

Mar 23 '11 at 12:04 AM AngryOldMan

all scripts applied to the player I mean!

Mar 23 '11 at 12:04 AM AngryOldMan
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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"); 
}
more ▼

answered Mar 22 '11 at 11:54 PM

efge gravatar image

efge
5.1k 5 14 38

The code I've set up right now goes 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"); } It instantiates the object, but nothing is added.

Mar 23 '11 at 12:00 AM 2Tie

edited my answer

Mar 23 '11 at 12:02 AM efge

Thanks! That helped a lot!

Mar 23 '11 at 12:19 AM 2Tie
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3316
x531
x202
x80

asked: Mar 22 '11 at 11:38 PM

Seen: 3972 times

Last Updated: Mar 23 '11 at 12:02 AM