- Home /
How to instantiate prefab when colliding with specified prefab
Hello, so I want this script to instantiate a prefab when colliding with a specified prefab. Right now my script is spawning the prefab whenever the object is colliding with anything:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class explosion : MonoBehaviour
{
public GameObject explosionPrefab;
public float explodeSecs = -1;
void OnCollisionEnter( Collision collision )
{
// Rotate the object so that the y-axis faces along the normal of the surface
ContactPoint contact = collision.contacts[0];
Quaternion rot = Quaternion.FromToRotation(Vector3.up, contact.normal);
Vector3 pos = contact.point;
Instantiate(explosionPrefab, pos, rot);
// Destroy the projectile
}
}
I can't figure it out how to edit the script, so I can specify in the inspector at which object-collision the script should spawn my prefab. Thanks for help in advance :)
Answer by xxmariofer · Jun 26, 2020 at 01:59 PM
the simplest solution is to add in the inspector a tag to the gameobjects you want them to collide and instantiate the explosion and inside the collision enter check the tag
void OnCollisionEnter( Collision collision )
{
if(collision.gameObject.tag != "TheCollisionTag")
return;
// Rotate the object so that the y-axis faces along the normal of the surface
ContactPoint contact = collision.contacts[0];
Quaternion rot = Quaternion.FromToRotation(Vector3.up, contact.normal);
Vector3 pos = contact.point;
Instantiate(explosionPrefab, pos, rot);
// Destroy the projectile
}
Your answer
Follow this Question
Related Questions
Box Collider 2d don't stop the object (prefab) 2 Answers
Putting prefab into scene messes with the transform origin? 1 Answer
Tagging object while instating not working. 3 Answers
Creating prefabs at runtime for debugging purposes 1 Answer
Deactivating one object trough script deletes all versions of it in scene 1 Answer