OnCollosionEnter not working

So I recently started coding and using Unity so I’m not the best at it and I was stuck on this one. I have no idea why this will not work but I’m sure there is just something I didn’t notice. If anyone can tell me what I did wrong that would be great. If you want to know what I am trying to do, im trying to make a layer that if crashed into displays your health bar dropping, so the image fill amount goes down to 0.

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class Collision : MonoBehaviour {
    void OnCollisionEnter (Collision col)
    {
        if(col.gameObject.name == "AircraftJet")
        {
            Image image = GetComponent<Image>();
            image.fillAmount = .0f;
        }
    }
}

The console error is
‘Script error: OnCollisionEnter
This message parameter has to be of type: Collision
The message will be ignored.’

The class name should be the problem, “Collision” is already used by the unit. Rename the class and the script and test to see if this is the error.

2 Likes

Unity already provides a class called ‘Collision’. You could do some workarounds, creating your own namespace and using an alias name, but as you’re just about to write that class yourself, rename it.
After that, the error shouldn’t appear anymore.

What actually happens in this situation: the parameter’s type is seen as your own Collision class, Unity ‘knows’ about the messages such as the OnCollisionXXXX ones and checks them, it expects to have Unity’s built-in type Collision (UnityEngine.Collision).

@DenisLemos Do you know why this is not working?

using UnityEngine;
using UnityEngine.UI;
using System.Collections;


public class CollisionJawn : MonoBehaviour {
    void OnCollisionEnter (Collision col)
    {
        if(col.gameObject.name == "AircraftJet")
        {
            Image healthBar = GetComponent<Image>();
            healthBar.fillAmount = .0f;
        }
    }
}

This is my new error:
NullReferenceException: Object reference not set to an instance of an object
CollisionJawn.OnCollisionEnter (UnityEngine.Collision col) (at Assets/Scripts/CollisionJawn.cs:12)
(And yes the file named Collision was renamed to CollisionJawn, not my idea)