- Home /
Best way to handle clicking on a GUI.DrawTexture?
As simple as the title says - I'm trying to make a clickable button with GUI.DrawTexture
, and it works perfectly fine. But OnGUI is called at least twice, so when I try the following:
void OnGUI() {
Rect someRect3 = new Rect (xpos, ypos, xsize, ysize);
if (someRect3.Contains (Event.current.mousePosition))
GUI.DrawTexture (xpos, ypos, xsize, ysize), buttonTexture6);
else
GUI.DrawTexture (xpos, ypos, xsize, ysize), buttonTexture5);
Basically, it just has an image that lights up (highlighted) when the user has their mouse over it. That works. Only thing is, when I try if (Input.GetMouseButtonDown(0))
, it will be called twice. Other than that, it works perfectly. So if it's called twice, will that make a big difference if it opens up a "gui menu"? Or is there an easier way to check if I click on that GUITexture?
Answer by Krishna Chittur · Jul 02, 2014 at 11:23 AM
I get that this answer is like a month late, but here goes:
As far as I know, there's no way to directly check whether someone is clicking on the GUI.DrawTexture. You can, as you've done, just check if they're in the rectangle. I would change GUI.DrawTexture((xpos, ypos, xsize, ysize), buttonTexture5)
to simply GUI.DrawTexture(someRect3, currentTex);
in the OnGUI() function. Then declare a new texture called currentTex as a Texture2D, and when they hover or whatever, just change the value of currentTex in the Update function. No need to do all the checking work in the OnGUI() function, it'll just set the texture to the latest value of currentTex.
Alternatively, you could just use the GUITexture directly instead of GUI.DrawTexture, but then you wouldn't be able to scale the size of the texture to the screen size, a problem if you're targeting multiple platforms. If that's the case, you can use the OnMouseEnter()
and OnMouseExit()
functions easily.
Another option is to just use GUI.Button(someRect,currentTex)
. You can check it out at the scripting API for it. The hovering and pressing is all automatic, so it saves a lot of headache, and it's scalable if you want.
Your answer
![](https://koobas.hobune.stream/wayback/20220613151027im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Load a sprite as a texture from. 1 Answer
Change Gui Textre to another overtime? and reset script when player passes through trigger 1 Answer
GUI.DrawTexture() into a Layer? 1 Answer
Reduce Draw call for Multiple GUI Textures with same Texture 1 Answer
Activate GuiTexture When Clicking on BoxCollider c# 1 Answer