- Home /
How to attach a script to an instantiated object?
Hi there. I've searched through many questions around here and cannot seem to get any of the script fragments I find to work in my favor. Here is part of the JS script I currently have set up:
var z : Transform;
function OnTriggerEnter(hit : Collider){
Instantiate(z, Vector3(3032.3,2781.8,3068.6),Quaternion.identity);
z = gameObject.AddComponent("yesz");
}
The instantiation of the object z works out just fine, but the script "yesz" never gets attached to it. Could someone tell me what I should do? Thank you.
Answer by tanoshimi · Mar 10, 2015 at 02:07 PM
Instantiate returns the instance you just created, and it's that you want to attach the component to, not your prefab "z".
var z : Transform;
function OnTriggerEnter(hit : Collider){
var objectYouCreate = Instantiate(z, Vector3(3032.3,2781.8,3068.6), Quaternion.identity);
objectYouCreate.AddComponent("yesz");
}
Ah, I see what you are saying. After studying and trying again and again, I've used your smarts and my research to develop a solution that finally works! The code you provided was just missing the "gameObject." portion.
var z : Transform;
function OnTriggerEnter(hit : Collider){
var objectYouCreate = (Gameobject) Instantiate(z, Vector3(3032.3,2781.8,3068.6), Quaternion.identity) ;
objectYouCreate.AddComponent("Your Script Name");
}
Answer by Clarinet · Mar 11, 2015 at 05:51 AM
Kudos go to tanoshimi:
function OnTriggerEnter(hit : Collider){
var objectYouCreate = Instantiate(z, Vector3(3032.3,2781.8,3068.6),Quaternion.identity);
objectYouCreate.gameObject.AddComponent("yesz");
Your answer
Follow this Question
Related Questions
How to add a component in a runtime instantiation? 1 Answer
Instantiate creating infinite clones 0 Answers
Can't add sprite to instantiated GameObject 2 Answers
Photon Instantiate a prefab and add script on it. 1 Answer
How do I get a CS script in assets to be a stored monobehaviour variable 1 Answer