using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OnCollision : MonoBehaviour
{
public Transform other;
public GUIStyle style;
public GameObject crate1;
public GameObject GameObject2;
void OnGUI()
{
if (other)
{
float dist = Vector3.Distance(other.position, transform.position);
if(dist < 20 )
{
if (GUI.Button (new Rect (600, 100, 100, 100), "NO")) {
Destroy(crate1);
Destroy(GameObject2);
}
if (GUI.Button (new Rect (800, 100, 100, 100), "YES")) {
GUI.TextArea (new Rect (600, 250, 600, 400), "YOU GOT...", style);
GUI.Button(new Rect (600, 100, 300, 300), "OK");
}
GUI.TextArea(new Rect (600, 250, 300, 100), "Do You Want To Open This Crate?", style);
}
}
}
}
This is my code. When I press the no button, I was able to destroy the objects I want. But when I press the yes button, the same type of code doesn’t work. It is supposed to create a new button and text, but it doesn’t seem to work. My question is why and how can I fix it?
private bool isPressed = false;
void OnGUI()
{
if (other)
{
float dist = Vector3.Distance(other.position, transform.position);
if(dist < 20 )
{
if(this.isPressed == false)
{
if (GUI.Button (new Rect (600, 100, 100, 100), “NO”))
{
Destroy(crate1);
Destroy(GameObject2);
}
if (GUI.Button (new Rect (800, 100, 100, 100), “YES”))
{
this.isPressed = true;
}
}
else if(this.isPressed == true)
{
GUI.TextArea (new Rect (600, 250, 600, 400), “YOU GOT…”, style);
GUI.Button(new Rect (600, 100, 300, 300), “OK”);
}
GUI.TextArea(new Rect (600, 250, 300, 100), “Do You Want To Open This Crate?”, style);
}
}
}
GUI.Button returns true on the press so it only returns true for one frame. Then it will draw for that one frame and next frame the GUI.Button is back to false.
So if you set a variable and then check its state, you can display your UI accordingly.
Side-note: you are using OnGUI which is legacy and is known for being slow. You should give a try to the UI system.
void OnGUI()
{
if (other)
{
float dist = Vector3.Distance(other.position, transform.position);
if(dist < 20 )
{
if(this.isPressed == false)
{
if (GUI.Button (new Rect (600, 100, 100, 100), “NO”))
{
Destroy(crate1);
Destroy(GameObject2);
}
if (GUI.Button (new Rect (800, 100, 100, 100), “YES”))
{
this.isPressed = true;
}
GUI.TextArea(new Rect (600, 250, 300, 100), “Do You Want To Open This Crate?”, style);
}
else if(this.isPressed == true)
{
GUI.TextArea (new Rect (475, 100, 600, 400), "YOU GOT...", style);
if (GUI.Button (new Rect (700, 500, 100, 100), "OK")) {
this.isPressed = true;
}
}
}
}
}
}
So I have improved the code. When I press the yes button, the OK button and the text appear. But when I put the ok button in an if statement to make it disappear along with the text on click, it messes up the scene. Maybe I placed it in the wrong place. Any ideas?