- Home /
Placing HUD item on top right with respect to screen resolution
Hi I have been using unity for quite some time, but most of the time i have never needed to use a HUD as most of it is just research based. However, i am doing a project for my final year at my university. I have been trying to place a HUD item on the top right with respect to the screen resolution. At the moment i can place the HUD item on the top right with respect to my own screens resolution, but when i change resolution it moves out of place.
Here is the code i have at the moment : (I did find this code on the unity community. However the HUD item still moves when the screen resolution changes.)
void Awake() { myGUITexture = this.gameObject.GetComponent("GUI-HEART") as GUITexture; } void Start() { int ScreenHeight = Screen.height; int ScreenWidth = Screen.width; int textureHeight = 48; int textureWidth = 258; int screenAspectRatio = (ScreenWidth / ScreenHeight); int textureAspectRatio = (textureWidth / textureHeight); int scaledHeight; int scaledWidth; if (textureAspectRatio <= screenAspectRatio) { // The scaled size is based on the height scaledHeight = 48; scaledWidth = (ScreenHeight * textureAspectRatio); } else { // The scaled size is based on the width scaledWidth = 258; scaledHeight = (scaledWidth / textureAspectRatio); } float xPosition = ScreenWidth * 0.8f; //myGUITexture.pixelInset = new Rect(xPosition, scaledHeight - scaledHeight, //scaledWidth, scaledHeight); GameObject.Find("GUI-HEART").guiTexture.pixelInset = new Rect( xPosition, (float)( ScreenHeight - scaledHeight ) / 2.0f, scaledWidth, scaledHeight ); //pos = GameObject.Find("GUI-HEART").guiTexture.pixelInset; //pos.y = ScreenHeight / 2; // pos.x = ScreenWidth / 2; //GameObject.Find("GUI-HEART").guiTexture.pixelInset = pos; } void Update () { if (player.Hearts == 4) { guiTexture.texture = HeartsFull; } else if (player.Hearts == 3) { guiTexture.texture = ThreeHearts; } else if (player.Hearts == 2) { guiTexture.texture = TwoHearts; } else if (player.Hearts == 1) { guiTexture.texture = OneHeart; } else { guiTexture.texture = HeartsEmpty; }
Thats all the code for my placement of my HUD item.
Any help would be awesome. Especially if you have done it before. Thanks :)
EDITS : Doesn't work means that the HUD item still moves whenever the screen resolution is changed. E.G. it is at the right of my screen resolution, but when the screen resolution changes it moves rather than staying at the right.
Please format your code correctly.
What does "it doesn't work" mean?
After some more work it was pretty obvious to my face. The answer was staring at me. Simple way is just to put the xposition at ScreenWidth - ANU$$anonymous$$BER. Thanks for answers