- Home /
Applying random forces to all instantiated gameobjects
OnDeath of my character I'm disabling him and instead instantiate 6 prefabs of smaller balls to give it a look of an explosion, but I want to fly those 6 prefabs all over the place, like to add random force to each other them, so each flies randomly to some side.
foreach (GameObject i in obj) { Instantiate(i, transform.position,Quaternion.identity); i.rigidbody2D.AddForce(new Vector2(Random.Range(-10f,10f), Random.Range(-10f,10f)), Force$$anonymous$$ode2D.Impulse); } I tried something like that obj is the GameObject[] with 6 prefabs in it
Each time through your loop, Instantiate creates a new object, a clone of the i
prefab. But then you apply your force to i
ins$$anonymous$$d of to the new object. Try something like
foreach (GameObject i in obj)
{
GameObject g = Instantiate(i, transform.position,Quaternion.identity) as GameObject;
g.rigidbody2D.AddForce(new Vector2(Random.Range(-10f,10f), Random.Range(-10f,10f)), Force$$anonymous$$ode2D.Impulse);
}
Answer by fafase · Apr 27, 2015 at 07:32 PM
Try this:
http://docs.unity3d.com/ScriptReference/Rigidbody.AddExplosionForce.html
then you can change the material and/or rigidbody values so that they seem to get random forces. Some will go further than others.
THat's exactly what I was looking for. the problem is I'm developing a 2D game, and theres not Rigidbody2D.AddExplosionForce, anything similar to this for 2D?
Your answer
![](https://koobas.hobune.stream/wayback/20220613194203im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Kicking object with random direction and force 2D 0 Answers
Random instantiate at same frame with each instantiate having unique random direction 1 Answer
Semi Random Monster Spawner 3 Answers
using Switch and Case for 50% chance of occurance? C# 3 Answers
Teleporting camera and gameobjekt togather at random? 0 Answers