- Home /
Adding Functions to GUI Buttons?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class OnCollision : MonoBehaviour { public Transform other; public GUIStyle style;
void OnGUI()
{
if (other)
{
float dist = Vector3.Distance(other.position, transform.position);
if(dist < 15 )
{
GUI.Button(new Rect(600, 100, 100, 100), "NO");
GUI.Button(new Rect(800, 100, 100, 100),"YES");
GUI.TextArea(new Rect (600, 250, 300, 100), "Do You Want To Open This Crate?", style);
}
}
}
}
I have this code that makes 2 GUI Buttons and 1 GUI Text appear on collision. I have two buttons called "YES" and "NO". I also have a crate in the game. When I click the no button, I want the crate to disappear. When I click the yes button, I want the crate to open with a certain animation. How can I implement it into this code?
Answer by fafase · Oct 12, 2016 at 08:30 AM
This is the legacy UI which you should avoid for in-game UI.
https://docs.unity3d.com/ScriptReference/UI.Button.html
For your answer, GUI.Button returns true if pressed so you can set it in an if- statement:
if(GUI.Button(rect, text))
{
MethodToBeCalled();
}
Thank you so much. It worked for the "NO" button but my problem with the yes button is a little bit different. When I press the "YES" button, I want my game object which is the crate to open up with a certain animation. A text will come up saying YOU GOT... The crate will open up and a wheel will start to spin on the screen, and you gain a reward after you open it. And there will be an O$$anonymous$$ button at the bottom to exit that panel. After it's done, the crate will be destroyed. How can I implement it into my code?
your question says "Adding a function to GUI". Not "the crate to open up with a certain animation. A text will come up saying YOU GOT... The crate will open up and a wheel will start to spin on the screen, and you gain a reward after you open it. And there will be an O$$anonymous$$ button at the bottom to exit that panel. After it's done, the crate will be destroyed."
You're kinda falling into the "Code for me" section. Try some of it. And when you face a problem, ask about it. if you don't know where to start, then start easier.
Your answer
Follow this Question
Related Questions
OnSelect and OnPointerEnter work in one script but not another on the same object 2 Answers
Help with UnityException Error 1 Answer
Function Update and error UCE0001 3 Answers
GetButton Problem 1 Answer
Loop a Function a Random Number of Times 2 Answers