- Home /
Can't move GUI
I'm trying to get a GUI health bar in my 2-player game. After reading through many similar questions on this site, I still can't find a way to resolve this issue.
I was looking on the Unity GUI Scripting Guide to find how to make a health bar, and it gives this code:
var bgImage : Texture2D; // background image that is 256 x 32
var fgImage : Texture2D; // foreground image that is 256 x 32
var playerEnergy = 1.0; // a float between 0.0 and 1.0
function OnGUI () {
// Create one Group to contain both images
// Adjust the first 2 coordinates to place it somewhere else on-screen
GUI.BeginGroup (Rect (0,0,256,32));
// Draw the background image
GUI.Box (Rect (0,0,256,32), bgImage);
// Create a second Group which will be clipped
// We want to clip the image and not scale it, which is why we need the second Group
GUI.BeginGroup (Rect (0,0,playerEnergy * 256, 32));
// Draw the foreground image
GUI.Box (Rect (0,0,256,32), fgImage);
// End both Groups
GUI.EndGroup ();
GUI.EndGroup ();
}
I'm assuming this works just fine if it were singleplayer, but that is not what I want. So since I have splitscreen, I thought I should make 2, and move one of them to the other side of the screen. This doesn't work, as whenever I try to move it, the box just splits the background and foreground and/or stretches all over the place and doesn't work (see image)
This is the code I wrote that i thought would let me be able to adjust its' position:
var bgi : Texture2D;
var fgi : Texture2D;
var hitCounterCheck : int;
var otherScript : TankScript;
var otherObject : GameObject;
var posW : int;
var posH : int;
function Awake (){
otherObject = gameObject.Find("Player 1");
otherScript = otherObject.GetComponent(TankScript);
}
function Update () {
hitCounterCheck = otherScript.hitCounter;
}
function OnGUI(){
GUI.BeginGroup (Rect (posW,posH,posW+256,posH+20));
GUI.Box (Rect (posW,posH,posW+256,posH+20), bgi);
GUI.EndGroup();
GUI.BeginGroup (Rect (posW,posH,hitCounterCheck * 51+posW,posH+20));
GUI.Box (Rect (posW,posH,posW+256,posH+20), fgi);
GUI.EndGroup();
}
But that just causes the image below, where the first group stays at 0,0, and refuses to move. How can I get them both to move where I need?
Answer by Calumcj · May 10, 2012 at 09:25 AM
Hey, im still new to this but i will have a go :) You are setting your possisions with a in game edit fromt he inspecter panel. what would could try doing witht he possisioning is setting the co-ordanets in the script. e.g to make a box
function OnGUI () {
GUI.box(Rect ( 10, 30, 100, 50)"") {
}
}
This seems to work for me, so it might be worth a go :) (you can text in the box in the "" :))
Please, format your code properly. It makes things much more readable.