Search code examples
c#collision-detectioncollisionunity-game-engine

On-collision script not working?


in advanced I would like to say if this is a really simple question with a simple answer, I apologize as I have just now gotten into programming.Basically, I'm trying to create a script that a block named blue(picture below) on collision with the FPSController, will get destroyed, here is my script:

using UnityEngine;
using System.Collections;

public class Cube : MonoBehaviour {

    void OnCollisionEnter (Collision col) {

        if(col.gameObject.name == "Blue") {

            Destroy(col.gameObject);
            print ("collison detected");

        }

    }

}

for some reason, though, whenever the fps controller collides with the object known as "Blue" nothing happens, the print() function is not triggered nor is the destroy() function enter image description here

Thank you in advaned ;)


Solution

  • Rigidbody` is missing from your Cubes.

    1.Attach Rigidbody component to both cubes.

    2.Also,set both Cubes Rigidbody to Is-kinematic. You must set both Cubes Rigidbody to Is-kinematic so that the Character Controller wont be able to move it. Note that if your cube is falling down after adding Rigidbody, simply disable Use Graivty on the Rigidbody.

    Important:

    3.Delete FPSController. Since you will be interacting with other Rigidbody GameObjects, use RigidBodyFPSController. It can be found in Assets\Standard Assets\Characters\FirstPersonCharacter\Prefabs. Drag RigidBodyFPSController to the Scene then attach Cube script to it.

    You will notice there is a Rigidbody attached to RigidBodyFPSController. Don't modify the settings of it.

    That's it. Everything should be working as expected.

    Cube settings:

    enter image description here

    RigidBodyFPSController Settings:

    enter image description here