0
\$\begingroup\$

I'm trying to get an image to show in Unity based on a certain criteria. I would like the position of the image to be randomized every time on play.

However since GUI.DrawTexture shows the image for a single frame only, I end up with the image flashing across the screen in random areas. I would the first location to be randomized and the image to remain still there.

Any advice on how to perform this will be greatly appreciated.

Code:

void OnGUI(){
 if(HP>=0.9f){
   GUI.DrawTexture(new Rect (Random.Range(0,1000), Random.Range(0,700), 500, 300) aTexture);
  }
}
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

You need to store the random position outside the scope of your OnGUI method. If the position is already set, use the set position, otherwise create a new one.

Rect textureRect;
bool positionSet = false;

void OnGUI(){
    if(HP>=0.9f){ //We need to draw the texture
        if(!positionSet) { //Is the position already set? If not, set it
            textureRect = new Rect (Random.Range(0,1000), Random.Range(0,700), 500, 300);
            positionSet = true;
        }
        //Draw using the position set above or in a previous frame
        GUI.DrawTexture(textureRect, aTexture);
    } else {
        //If not drawing the texture unset the position so it's random for next time
        positionSet = false;
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ Hi, thanks for script. If I'm looking to do the same things for a bunch of images in an array, what should I be looking to change. (The images are to pop up as the game progress with all images in the array showing at the end) \$\endgroup\$
    – user4985
    Aug 14, 2014 at 14:25
  • \$\begingroup\$ Do you understand the concept here? Storing the position outside the scope of the OnGUI method? I think if you understand how that works, it's not too difficult to expand that to multiple images. I would likely create a class that holds: the image, that image's rectangle and if the position has been set. Then instead of an array of images, keep an array of the new class, where each object contains all the information you need. \$\endgroup\$
    – House
    Aug 14, 2014 at 14:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .