- Home /
Player not taking damage on collision with enemy
I'm having a strange issue where my player is not taking any damage when colliding with the enemy. I have Rigidbody 2D set to both of them and the appropriate tags set, but somehow my player is not taking any damage. I am at a loss, could the sprites im using cause this?
PlayerHealthController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHealthController : MonoBehaviour
{
public static PlayerHealthController instance;
private void awake()
{
instance = this;
}
//[HideInInspector]
public int currentHealth;
public int maxHealth;
// Start is called before the first frame update
void Start()
{
currentHealth = maxHealth;
}
// Update is called once per frame
void Update()
{
}
public void DamagePlayer(int damageAmount)
{
currentHealth -= damageAmount;
if(currentHealth <= 0)
{
currentHealth = 0;
gameObject.SetActive(false);
}
}
}
PlayerDamage
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamagePlayer : MonoBehaviour
{
public int damageAmount = 1;
private void onCollisionEnter2D(Collision2D other)
{
if(other.collider.gameObject.tag == "Players")
{
DealDamage();
}
}
private void onTriggerEnter2D(Collider2D other)
{
if(other.tag == "Players")
{
DealDamage();
}
}
//health controller
void DealDamage()
{
PlayerHealthController.instance.DamagePlayer(damageAmount);
}
}
Answer by swanne · May 12 at 11:52 AM
Hey,
Sorry for starting to answer your question with a question but why are you using both CollisionEnter2D and TriggerEnter2D?
Are any of the collider components setup as triggers in the inspector?
I think it would work using only CollisionEnter2D
I recommend doing a Debug.Log process of elimination on contact points in your functions to find where the 'break in the wire' is.
For example, in your PlayerHealth Controller script, as the first line under the Damage Player function put a Debug.Log("PlayerHealth Controller, Damage Player function called and damage amount of " + damageAmount + " passed through");
This will confirm that the code in the PlayerDamage script is working enough to access the first script and pass data to it.
Similar thing in your PlayerDamage script
Before the IF statement add a line to confirm that the collision method is being called. Something like Debug.Log("CollisionEnter2D called");
It may seem a long process but I find it really useful to isolate the problem and understand where in the process I should be focusing on to fix.
Hope that helps
Your answer
Follow this Question
Related Questions
multiple objects on oncollissionstay2d 1 Answer
How to set collision for an object with specific collider size? 3 Answers
2D colliders not work 1 Answer
Collision detection problem 0 Answers
Workarounds for Higher Control When Using Physics2D? 0 Answers