- Home /
attaching a script at runtime to an element of GameObject array
Hello everyone, I have just tried gameObject.AddComponent("changeCursonOnHover") to a prefab which is added at runtime, and works fine!
When I use the array, everythings works fine except the model.AddComponent("changeCursonOnHover");
This script is attached to an empty gameObject and attached my prefabs to the array elements.
var arrayOfModels:GameObject[]; function Start () {
var randomNumber:Number = Mathf.Round(Random.value * 2);
var model:GameObject = Instantiate(arrayOfModels[randomNumber], transform.position,transform.rotation) as GameObject;
model.transform.parent = transform;
model.AddComponent("changeCursonOnHover");
}
Please some help!
What doesn't work? What's the error message or behavior?
Remove the "" before and after the scriptname in model.AddComponent.
Answer by Drakestar · May 26, 2012 at 12:03 AM
var arrayOfModels:GameObject[];
It doesn't look like you're ever adding any elements to the array, so you're likely instantiating Null. Add a test for null after the Instantiate() call and see if you get anything.
@$$anonymous$$atthias Worch , I can see my models appear on screen, which means the instantiate has worked properly. also model.transform.parent = transform; works fine , sine the parent is rotating around itself, and the instantiated model are rotating too, it only fails on the addcomponent
Your answer

Follow this Question
Related Questions
How to randomly instantiate other prefabs parallel? 1 Answer
Instantiate prefab within parameters?(Javascript) 1 Answer
Destorying prefab and instanstiating again? 0 Answers
Instantiate PreFab with C# Script 5 Answers
Instantiate A Prefab 1 Answer