Search Unity

How to run script only when colliding with defined prefabs?

Discussion in 'Scripting' started by unity_i18-uT700nXG_Q, Jun 24, 2020.

  1. unity_i18-uT700nXG_Q

    unity_i18-uT700nXG_Q

    Joined:
    Jun 15, 2020
    Posts:
    1
    Hi, I'm pretty new to Unity and this problem really drives me crazy...

    Basically, I have the following script to be executed only when prefab "a" collides with prefab "c". But the script should not run when prefab "a" collides with prefab "b", as this doesn't match my game idea.

    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
    }
    }

    Right now, I can't figure out how to run scripts on these special events... Any help is appreciated.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Use [code ]code tags[/code] when posting code.

    The collision parameter that is being sent contains all sorts of information about the thing you collided with, so you can do something like:
    Code (csharp):
    1.  
    2. void OnCollisionEnter( Collision collision )
    3. {
    4.    if (collision.gameObject.GetComponent<ScriptThatIsOnPrefabC>() != null) {
    5. ...
    As one example. You could also check its tags, its layer, its name (though that's a bad idea), anything.