# Unity 5 C# collision problems

I want to make the built-in FPS controller collide with an object and switch a boolean to true. Here is my code:

public static bool WellGUIOn;

// Use this for initialization
void Start () {
WellGUIOn = false;
}

void OnCollisionEnter (Collision c)
{
if (c.gameObject.name == "Well") {
WellGUIOn = true;
} else {
WellGUIOn = false;
}


I have attached this script to the FPS controller and added a box collider on both prefabs (with is trigger ticked). The FPS controller already has a rigidbody(with kinematic ticked) and I added a rigidbody (with kinematic NOT ticked) to the object. Unfortunately, it doesn't work. How can I solve this?

• How it does not work? Can you give us more information? Have you set breakpoint inside OnCollisionEnter that does that event even get called? – Jon Koivula Oct 19 '15 at 18:34
• @Jon Koivula it doesn't work because the boolean doesn't get set to true. – DubGamer87 Oct 20 '15 at 7:20
• Have you set breakpoint to that if line and see if the code does get there when colliding with prefabs. – Jon Koivula Oct 20 '15 at 11:21
• @JonKoivula No, I haven't. Anyway, I might seem like a bit of a noob but how? – DubGamer87 Oct 20 '15 at 16:38
• Google how to use breakpoints when debuggin. When you know how to do it, then you can see if that function is fired. – Jon Koivula Oct 20 '15 at 18:45

First of all, it is always a good idea to use Debug.Log() when something goes wrong.

void OnCollisionEnter (Collision c)
{
Debug.Log("Collision: " + gameObject.name + " | " + c.gameObject.name);
if (c.gameObject.name == "Well") {
WellGUIOn = true;
} else {
WellGUIOn = false;
}


You can now see if the function is called the way you intended.

added a box collider on both prefabs (with is trigger ticked)

Assuming you are using 3D and not 2D, I think you might want to use OnTriggerEnter() instead of OnCollisionEnter() then?

void OnTriggerEnter(Collider c)
{
Debug.Log("Trigger: " + gameObject.name + " | " + c.gameObject.name);
if (c.gameObject.name == "Well") {
WellGUIOn = true;
} else {
WellGUIOn = false;
}


If you want to read more about Unity's collision system, here's the Colliders Overview.

• Thank you! In reply to the first bit, Jon Koivula said to use the breakpoint feature. – DubGamer87 Oct 21 '15 at 16:06

In 2d mode, you must use OnCollisionEnter2D.

Example:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour  {

void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Enemy")
coll.gameObject.SendMessage("ApplyDamage", 10);
}

}

• I'm not using 2d, but thanks. I'll use this for the future. – DubGamer87 Oct 21 '15 at 16:04