What I’m asking was really simple for me to do in other game engines but I haven’t really gotten around to get it to work in Unity.
I’m trying to get all the enemies in my game to display the value of their health variable on top of them at runtime. There can be multiple instances of the same enemy in the game at the same time and most of these objects get instantiated during runtime.
The code I that I have for the enemy so far:
using UnityEngine;
using System.Collections;
public class CreatureScript : MonoBehaviour
{
public int dir = 0;
public int changetime = -1;
private int timer = 0;
public int mspeed = 2;
public int side = 0;
public int health = 2;
public int attack = 1;
CreatureScript creatureScript;
BulletScript bulletScript;
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "wall") //Collision with wall
{
mspeed = mspeed * -1;
}
if(other.tag == "creature") //Collision with creature
{
mspeed = mspeed * -1;
CreatureScript creatureScript = other.GetComponent<CreatureScript>();
if(side != creatureScript.side)
{
health -= creatureScript.attack;
if(health < 1)
{
Destroy(gameObject);
}
}
}
}
void FixedUpdate ()
{
if(timer == changetime) //set random direction
{
timer = 0;
dir = Random.Range(0,4);
}
timer = timer + 1;
//Change direction
if(dir == 0)
transform.Translate (new Vector3(mspeed*Time.deltaTime,0*Time.deltaTime,0));
if(dir == 1)
transform.Translate (new Vector3(-mspeed*Time.deltaTime,0*Time.deltaTime,0));
if(dir == 2)
transform.Translate (new Vector3(0*Time.deltaTime,mspeed*Time.deltaTime,0));
if(dir == 3)
transform.Translate (new Vector3(0*Time.deltaTime,-mspeed*Time.deltaTime,0));
}
}
I already tried playing around with the new UI System but haven’t really found an option that makes this work yet.
Thanks for your answers in advance.