- Home /
How to Instantiate Prefab as Child of Player OnTriggerEnter
Hello, I am a Unity beginner and have been searching for a while without success. I have a CharacterController named "Player" that I would like to have run into a trigger GameObject(which I place my JavaScript onto). I would then like for OnTriggerEnter to instantiate a prefab (this will be the Flame prefab in Unity_StandardAssets_Particles_Fire). I can get this to work, but I want the prefab to then become a child of the "Player" so that it stays on my character. I have tried the following code which successfully instantiates the prefab OnTriggerEnter (it just stays with my trigger GameObject and does not become a child of my "Player". I am getting an error:
"InvalidCastException: Cannot cast from source type to destination type."
My Code:
var instantiation : Transform; var player: Transform;
function OnTriggerEnter (other : Collider)
{
if(other.gameObject.name=="Player"){
var newPrefab : Transform;
newPrefab = Instantiate (instantiation, transform.position, transform.rotation);
newPrefab.parent = player;
newPrefab.localRotation = Quaternion.identity;
}
}
Thanks for any Help!
Your answer
Follow this Question
Related Questions
Make a simple tree 1 Answer
Prefab, procedural attachment of child, childCount return 0 1 Answer
Instantiate a Prefab as child 0 Answers