- Home /
How do I script a GUI Texture as a button, if it's being called from a public variable? [C#]
I have a simple UI Set up, that uses a few GUI Texture on Screen, to act as the player controls. I want to simply say, "When this GUITexture is Pressed, Do this". Here's my problem. To make it way easier on me, I'm using Public variables in a "Master Script". So I can simply drag an drop all of my textures into the inspector, and everything is set up for me. How can I call OnMouseDown (Or something similar) on these GUITexture variables? Thanks!
You could assign an own script to each of the GUITexture's and have the On$$anonymous$$ouseDown inside those scripts (might require a collider per texture object), then you could either handle the click in their script or call a custom function in your master script that would handle the clicks based on what was clicked.
I was really hoping I wouldn't have to do that.. Does anyone know any way I can keep all the code in one script?
Are you trying to avoid the colliders? Could cast a raycast from mouse position and use a switch to check for the texture that has been hit. By the way I would still go with xortrox's solution. You can have a script that On$$anonymous$$ouseDown calls a master script and pass as a parameter it's on gameobject, then on the master script just compare with the ones you have to check which one has been clicked.
I decided to go with that solution. It worked, but Now I'm having a new issue (Not sure if it's related or not..) I can only click on the lower half of my button. The top half is unresponsive. Any ideas?
I would suspect the collider isn't taking up the space it should other than that I'm not really sure.
Answer by xortrox · May 06, 2014 at 02:32 PM
This is my example of how I would do it
Script per GUITexture:
public class GUITextureClick : MonoBehaviour
{
MasterScript masterScript;
void Start()
{
//Obviously has to be changed to fit your setup
masterScript = GameObject.Find("/MyMasterScriptObject").GetComponent<MasterScript>();
}
void OnMouseDown()
{
MasterScript.OnMouseDown(this.gameObject);
}
}
Your master script would implement this function:
public void OnMouseDown(GameObject sender)
{
switch(sender.transform.name)//One way to check which texture got clicked
{
case "Button1":
break;
}
}
All you would have to do now is assign the GUITextureClick component to all textures, if you think THAT would be a hassle then that's also quite simple, just select all of them and assign the component through the component menu: Component->Scripts->GUITextureClick once it's added to your project.