I want to create a script that can work both on my player units, and also on my enemy units.
The problem is that the units receive damage, but the value of it is set on themselves.
For example i got a player unit with dmg set to 10, and if it encounters enemy this unit is losing 10 hp every ‘hit’. I tried bunch of thing with tags etc, but nothing was working.
Since I can’t figure it out by my self if there is a way to do that without separating the script for ‘player atk’ and ‘enemyatk’ as well as ‘playerhp’ and ‘enemyhp’, here is my code to atk, and hp script, please at least guide me on the right track.
ATK SCRIPT:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Atk : MonoBehaviour {
public float timeBetweenAttacks = 0.5f;
public int minDmg;
public int maxDmg;
GameObject mob;
GameObject player;
private Health health;
bool playerInRange;
bool mobInRange;
float timer;
void Awake ()
{
player = GameObject.FindGameObjectWithTag ("Tower");
mob = GameObject.FindGameObjectWithTag ("Mobs");
health = GetComponent<Health> ();
}
void OnTriggerEnter (Collider other)
{
if(other.gameObject == player)
{
playerInRange = true;
}
if(other.gameObject == mob)
{
mobInRange = true;
}
}
void OnTriggerExit (Collider other)
{
if(other.gameObject == player)
{
playerInRange = false;
}
if(other.gameObject == mob)
{
mobInRange = false;
}
}
void Update ()
{
timer += Time.deltaTime;
if (timer >= timeBetweenAttacks && playerInRange == true && health.currentHealth > 0)
{
Attack ();
}
if (timer >= timeBetweenAttacks && mobInRange == true && health.currentHealth > 0)
{
Attack ();
}
}
void Attack ()
{
timer = 0f;
if(health.currentHealth > 0)
{
health.TakeDamage (Random.Range (minDmg, maxDmg));
}
}
}
HP SCRIPT
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Health : MonoBehaviour {
public int startingHealth = 100;
public int currentHealth;
bool isDead;
void Awake ()
{
currentHealth = startingHealth;
// healthSlider.maxValue = startingHealth;
}
public void TakeDamage (int amount)
{
currentHealth -= amount;
// healthSlider.value = currentHealth;
if(currentHealth <= 0 && !isDead)
{
Destroyed ();
}
}
void Destroyed ()
{
isDead = true;
Destroy(this.gameObject);
}
}