- Home /
Question by
TimeStopperGames · Nov 04, 2018 at 01:20 AM ·
playerdamageenemy aihealth-deductionhealth
how to make enemy damage player?
im trying to make a script so that when the enemy is close enough to the player (since its a melee attack) it takes a point of damage off the player every amount of time. Enemy Script: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Enemy : MonoBehaviour {
public int health;
public float speed;
public GameObject BloodEffect;
public bool FindPlayer;
public Animator enemyAnim;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(health <= 0)
{
Destroy(gameObject);
}
transform.Translate(Vector2.left * speed * Time.deltaTime);
}
public void TakeDamage(int damage)
{
Instantiate(BloodEffect, transform.position, Quaternion.identity);
health -= damage;
Debug.Log("Damage Taken");
}
void GiveDamage()
{
if (FindPlayer)
{
if (GameObject.FindGameObjectWithTag("Player"))
{
GetComponent<HealthSystem>().Damaged();
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
FindPlayer = true;
}
}
Player Health Script: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class HealthSystem : MonoBehaviour
{
public int health;
public int numOfHearts;
public Image[] hearts;
public Sprite fullHeart;
public Sprite emptyHeart;
void Update()
{
if (health > numOfHearts)
{
health = numOfHearts;
}
for (int i = 0; i < hearts.Length; i++)
{
if (i < health)
{
hearts[i].sprite = fullHeart;
}
else
{
hearts[i].sprite = emptyHeart;
}
if (i < numOfHearts)
{
hearts[i].enabled = true;
}
else
{
hearts[i].enabled = false;
}
//if (health > 0)
//{
// Destroy(gameObject);
// }
}
}
public void Damaged()
{
health -= 1;
if (health < numOfHearts)
{
numOfHearts = health;
}
}
}
any help would be great thanks =)
Comment
Best Answer
Answer by zxc76_die · Nov 04, 2018 at 02:00 AM
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.transform.name == "Player")//or tag
{
collision.GetComponent<HealthSystem>().Damaged();
}
}
Maybe so? This needs to be added to the enemy.