I currently have the framework in place to have a bunch of little enemies, all with their own health, and I was wondering how I would go about creating health bars that hover over their heads?
Ive got code that creates a GUI rect that scales with the players health, but the GUI stuff uses a different coordinate system(or so I think) that makes it difficult to center over the enemies.
Is there any easy way anyone can think of to create health bars that hover over the enemies on screen?
cam = GameObject.FindWithTag("Main Camera");// Try finding it with a tag instead
if (cam)// Make sure it exists, if it doens't this will get rid of the NullReferenceException all the same
{
ac = cam.camera.WorldToScreenPoint(gameObject.transform.position); //y-coordinate system needs to be inversed because 0-0 is top left
float y = ac.y;
y = Screen.height-y;
ac.y = y; //Define rectangle, x, y, width, height
Rect myRect = new Rect(ac.x-20,ac.y-30,50,3);
displaybar = myText1;
Debug.Log(myRect);
Debug.Log(displaybar.width);
Debug.Log(displaybar.name);
GUI.DrawTexture(myRect, displaybar, ScaleMode.ScaleAndCrop, false, 0);
}
well i think i know the error the script look fine but i think the reason why its not working is because your Main camera dont have the same name as the one in the script so thats why the script cant find the object.
Thank you very much for your answer! I managed to figure it out :)
Now I am encountering another problem. Here is my code:
cam = GameObject.Find("Main Camera");
ac = cam.camera.WorldToScreenPoint(gameObject.transform.position);
//y-coordinate system needs to be inversed because 0-0 is top left
float y = ac.y;
y = Screen.height-y;
ac.y = y;
//Define rectangle, x, y, width, height
Rect myRect = new Rect(ac.x-20,ac.y-30,50,3);
displaybar = myText1;
Debug.Log(myRect);
Debug.Log(displaybar.width);
Debug.Log(displaybar.name);
GUI.DrawTexture(myRect, displaybar, ScaleMode.ScaleAndCrop, false, 0);
Sadly I get an error that says:
NullReferenceException: Object reference not set to an instance of an object
I am not sure what is generating this in the DrawTexture call, the myRect and displaybar seem to put out the right numbers in the debug log.