How can I detect only 1 collision between two clones of the same prefab?
Hi guys. In my game 2 monsters of the same type can bump into each other and merge into a bigger monster.
I use Instantiate inside OnTriggerEnter, but it spawns 2 new monsters because both objects collide with each other and trigger 2 collisions (which is expected).
How can I avoid this and spawn only one monster upon such collision?
Here is my code
void OnTriggerEnter (Collider other)
{
if (gameObject.name != other.gameObject.name)
return;
if (willMerge ()) {
Vector3 spawnPosition = gameObject.transform.position + gameObject.transform.position - other.gameObject.transform.position;
Quaternion spawnRotation = gameObject.transform.rotation * Quaternion.Inverse (other.gameObject.transform.rotation);
DestroyImmediate (gameObject);
DestroyImmediate (other.gameObject);
Instantiate (mergeMonster, spawnPosition, spawnRotation);
} else {
float angle = Quaternion.Angle (transform.rotation, other.transform.rotation);
transform.Rotate (0.0f, angle / 2, 0.0f);
}
}
willMerge is just a private function which can return true/false based on RNG. mergeMonster is a public GameObject linked to a prefab.
Your answer
Follow this Question
Related Questions
How to avoid collisions using InstanceID 0 Answers
Which of Mulitipe colliders OnCollisionEnter ? 0 Answers
Turret not spawning fireball via instantiation in Unity 2d? 0 Answers
Is there any good sample code for shooting a projectile and collision detection? 0 Answers
Collision Detection not working 4 Answers