- Home /
Enemy won't damage player C#
Hey, im kinda a beginner so i dont understand to complex stuff, but im trying to make a game with enemies. Im trying to make a script so my player takes damage while in the enemys attack range, the enemy has a box collider and is set to trigger thesse are my scritpts:
Enemy script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAttack : MonoBehaviour {
public bool inRange;
public float damage;
void Start ()
{
}
void Update ()
{
if(inRange == true)
{
//attack
PlayerStats player = GetComponent<PlayerStats>();
player.P_TakeDamage(damage);
}
}
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
inRange = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
inRange = false;
}
}
}
Player Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerStats : MonoBehaviour {
public float currHealth;
public float maxHealth;
void Start ()
{
}
public void P_TakeDamage(float ammount)
{
currHealth -= ammount;
}
void Update ()
{
if (currHealth > maxHealth)
{
currHealth = maxHealth;
}
if (currHealth <= 0)
{
//Die
Die();
}
}
public void Die()
{
Destroy(gameObject);
}
}
Answer by LCStark · Oct 11, 2018 at 07:17 PM
Does any of your objects have a Rigidbody component? Without it, the colliders won't do anything.
Is the collider on your player marked as "trigger" collider? If not, you have to use OnCollisionEnter and OnCollisionExit instead of OnTriggerEnter
and OnTriggerExit
.
Your answer
Follow this Question
Related Questions
Enemy wont damage player 0 Answers
Enemy wont damage player 2 Answers
Lerp in Coroutine (Crazy Behavior) 2 Answers
Run coroutine only when player stays inside collider? 0 Answers
Enemy Health Bar Fill (Unity2D) 2 Answers