OnMouseOver Tower Gui Health Bar

Hey everyone,

I have found unityanswers so helpful, but I have finally hit a brickwall and therfore this is my first post ever…

Like a lot of people, I am trying to create a TD / RTS. The first script below is to show a GUI when mouse is over the spawned “Enemy”. This script works perfectly as it only displays one Texture. The second script below is attached to the spawned “Player”. The issue im having is I have tried to implement a health system, that being that every time the health decreases on the “Player” by 1, the Texture changes to the Texture relating to the health amount. Currently it is at a point where the script will run, but the mouseover function is not working!!! Nothing appears, nor are there any errors at runtime… I would appreciate any help on this!!!


Enemy

var healthTex : Texture2D;
var health : int = 40;
var target : Transform;

private var _mouseOver = false;

function OnGUI()
{
    if(!_mouseOver) return;
    	var screenPos : Vector3 = Camera.main.WorldToScreenPoint(target.position);
		GUI.DrawTexture(Rect(screenPos.x - 25.0f,Screen.height - screenPos.y-50.0f,40,12), healthTex);

}
function OnMouseOver()
{
    _mouseOver = true;
}
function OnMouseExit()
{
    _mouseOver = false;
}

Player

var health : int = 5;
var target : Transform;

var h1  : Texture2D;
var h2  : Texture2D;
var h3  : Texture2D;
var h4  : Texture2D;
var h5  : Texture2D; 

var healthTex : Texture2D = h5;

private var _mouseOver = false;

function OnUpdate()
{
	
	if (health == 5)
	{
		healthTex = h5;
	}
	else if (health == 4)
	{
		healthTex = h4;
	}
	else if (health == 3)
	{
		healthTex = h3;
	}
	else if (health == 2)
	{
		healthTex = h2;
	}
	else if (health == 1)
	{
		healthTex = h1;
	}

//Enter health = 0 dah dah dah...

}

function OnGui()
{
    if(!_mouseOver) return;
    	var screenPos : Vector3 = Camera.main.WorldToScreenPoint(target.position);
		GUI.Box(Rect(screenPos.x - 25, Screen.height - screenPos.y, 40, 12), healthTex);
}	
	

function OnMouseOver()
{
    _mouseOver = true;
}
function OnMouseExit()
{
    _mouseOver = false;
}

I think the problem here might be that your OnUpdate function doesn’t get called. I think you mean to use Update().

If changing function names does not solve the problem you should check whether OnMouseOver gets called at all by adding Debug.Log into it. If it gets called the raycast probably just ignores the player and not the monsters because of some layer issue.

You are absolutely right!!! Also, function OnGui should be OnGUI… its very easy to miss things when you are constantly staring at code haha.

Thank you very much!