- Home /
How to spawn a prefab on a trigger?
Dear community,
Im working on a vertical 2D platformer, and i am trying to use if statements to trigger certain events in my game.
for example when the player hits a collider, i want to spawn a prefab(comet) with a constant force component added to it.
Ive tried all kinds of code, but i cant seem to make it work.
it is for a school project and would realy appreciatie any kind of help or advise.
Answer by greatestprez · Dec 20, 2012 at 09:22 PM
Make sure your prefab has a rigidbody attached to it, and try something like this (note that code hasn't been tested)
void OnTriggerEnter(Collider col) {
if (col.gameObject.tag == "MyTag") {
GameObject ref = Instantiate(myObj, myPosition, myRotation) as GameObject;
ref.GetComponent<Rigidbody>().AddForce(new Vector3(myForceX, myForceY, myForceZ) * mySpeed)
}
}
This method looks good! what kind of variables must i declare to make this work?
Thanks in advance!
you'd need a tag on the object interacting with your trigger ("$$anonymous$$yTag" in this example), a public variable to hold your comet prefab ("myObj" in this example), a quaternion and a vector3 to Instantiate the prefab with a position and rotation ("myPosition" and "myRotation" in this example), you need a rigidbody on your comet prefab, you 3 floats to move the comet in a direction("myForceX", "myForceY", "myForceZ" ), and you would also need a speed variable to make it move at a certain speed("mySpeed")
Answer by Tijs · Dec 27, 2012 at 10:25 PM
To make this work i used the Enable/Disable Component on trigger to call it in. and destroy(object,5) to make it disappear. But it seems i cant destroy a rigidbody that way.
Answer by TheRealKuha · May 18, 2016 at 07:26 PM
I found this video explaining it pretty good, also tells you how to spawn something that falls down, a rigidbody: https://www.youtube.com/watch?v=_Xrw2EEhzI4
Your answer
![](https://koobas.hobune.stream/wayback/20220613085721im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Children of Instantiated Prefabs are not seperate 1 Answer
Turning a menu on and off onclick in hololens 0 Answers
Move towards mouse position on button down (2D)? 1 Answer
How do I transform the position of my cube AWAY from the larger cube its attached to? 0 Answers
no velocity/force after build unity4 JS 0 Answers