Random Range in GUI box

Hello, I’ve made a GUI box and I want every time I play my game this GUI box be in a radom location. I’ve made this piece of code:

var a = 150;
var t = a++;

var b = 100;
var t1 = b++;

var curHealth = 200;
var maxHealth = 200;


function OnGUI(){
       GUI.Box(new Rect(Random.Range(a, b), Screen.height / 2 - m2 + 50, 100, 50),"Health: " + curHealth + "

Damage dealed:
" + (maxHealth - curHealth));
}

Everytime I play my game, the box shakes like crazy. How can I make it stay in one random position?

Any help is appriciated.

Thanks :slight_smile:

Call Random.Range once, such as in Awake or Start, not every frame in OnGUI.

Having the Random Range in the OnGUI code makes it constantly random. That’s why your box is shaking. To fix this, define a Rect in Awake or Start like so:

var a = 150;
var t = a++;
 
var b = 100;
var t1 = b++;
 
var curHealth = 200;
var maxHealth = 200;
 
var boxRect : Rect;
 
function Start()
{
    boxRect = new Rect(Random.Range(a, b), Screen.height / 2 - m2 + 50, 100, 50);
}
 
function OnGUI()
{
       GUI.Box(boxRect,"Health: " + curHealth + "

Damage dealed:
" + (maxHealth - curHealth));
}

Note: Not sure what “m2” is but it is not defined in the code you posted.