- Home /
Add a script to a gameobject that doesn't exist yet
I have a script that creates a cube but I need to add a script to that newly created cube. How would i do this?
Answer by CHPedersen · Jul 16, 2013 at 09:40 AM
Right after you create the cube (presumably using GameObject.CreatePrimitive?) you can add whatever component you want, including scripts, by calling AddComponent on the newly created object.
Like so:
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.AddComponent<YourScriptHere>();
Thanks for the answer. I really appreciate the vote up too.
when trying it I get "Assets/Standard Assets/Scripts/my scripts/Box$$anonymous$$aker.js(10,9): BCE0005: $$anonymous$$ identifier: 'Cube'." here is my code. error is on line 10
//to be used later
var cubeSpeed = 5;
function Start () {
//makes cube
var ss : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
//moves it to player
ss.transform.position = Vector3(1010.457, 3.351044, -584.6373);
//adds script to cube
Cube.AddComponent(Box$$anonymous$$aker);
}
You want to do:
ss.AddComponent(Box$$anonymous$$aker);
You are doing
Cube.AddComponent(Box$$anonymous$$aker);
See the difference?
Answer by TobyXD · Jul 16, 2013 at 09:44 AM
Use GameObject.AddComponent API to add Script to a GameObject.
In C#
ScriptClass scriptVar = (ScriptClass)newGameObject.AddComponent<ScriptClass>();
In Js
var scriptVar = newGameObject.AddComponent(ScriptClass);
Your answer

Follow this Question
Related Questions
How do I disable Script on FP Controller? (Solved) 2 Answers
destroy hinge joint component from another object in javascript 2 Answers
Why am I getting this error ? 2 Answers
Activate a component when an animation clip in an animator is played? 0 Answers
Script.Enabled does not work in Unity 5+ 2 Answers