Home > Software engineering >  GameObject not detecting Collision
GameObject not detecting Collision

Time:01-11

I have a player and ai enemy. When the enemy is within range of the player it Instantiate a projectile. My code (attached to the player) is supposed to detect the collision of the projectile with it's tag and decrease its health upon collision. My issue is that the player is not detecting any collisions even those outside the "if" statement.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;



public class bullet_hit : MonoBehaviour
{
    public int  maxHealth = 10;
    public int currentHealth;
    public HealthBar HealthBar;
      
    // Start is called before the first frame update
   public void Start()
    {
        currentHealth = maxHealth;
        HealthBar.SetMaxHealth(maxHealth);
        
    }
    // Update is called once per frame
   public void Update()
    {
        
     void OnCollisionEnter(Collision other)
    {
         Debug.Log("hit by"   other.gameObject.name);
         
        if (other.gameObject.tag == "Axe")
        {
             Debug.Log("hit by ball");
            TakeDamage(2);    
        }
}
void TakeDamage (int damage)
{
    Debug.Log("took damage");
    currentHealth -= damage;
    HealthBar.SetHealth(currentHealth);
}
}

}

I checked my ball for the correct tag. Both the player and ball have colliders and rigidbodies. And I've gone into the project settings at checked the layer collision matrix but all boxes were checked. I recieve no error messages. Player Rigid Body Player Collider Ball rigid body and collider

CodePudding user response:

You’ve put the OnCollisionEnter method within the Update method as a “local function”:

public void Update()
{
    void OnCollisionEnter(Collision other) // this is a “local function” inside Update
    {
        Debug.Log("hit by"   other.gameObject.name);
         
        if (other.gameObject.tag == "Axe")
        {
             Debug.Log("hit by ball");
            TakeDamage(2);    
        }
    }
}

When what you should do is:

public void Update()
{
    // any update code goes here ..
}
        
void OnCollisionEnter(Collision other)
{
    Debug.Log("hit by"   other.gameObject.name);
         
    if (other.gameObject.tag == "Axe")
    {
         Debug.Log("hit by ball");
         TakeDamage(2);    
    }
}

Unity is looking for class function called OnCollisionEnter, but because you put it inside the Update function, Unity couldn’t see it, and thus doesn’t call it.

  • Related