简体   繁体   中英

How to create a dialogue box and display it when an object in clicked in unity 3d?

I am relatively new to scripting and unity. How can i create a dialog box with "Yes" and "No" buttons and display it when a particular objects in unity 3d is clicked ?

Keep the Dialogue Text UI object and Button UI objects as children of an empty Rect/UI object.

在此输入图像描述

Use some code like below in the object that will be clicked:

void OnMouseDown()
{
 dialogueBoxUIObject.SetActive(true);
}

Keep the dialogueBoxUIObject a public GameObject so that you can assign it in inspector. Keep Collider and Rigidbody components with no gravity with the object you want to click on.

There's a good Unity tutorial on how to achieve a modal box here:

https://unity3d.com/learn/tutorials/modules/intermediate/live-training-archive/modal-window

It achieves what you need to do and also adds other components that might help you in the future. You can see all the code that's used for achieving the dialog box below the video.

You can use a Canvas Group to group inside it the dialog you want and both Yes/No buttons and set its Alpha to 0 and Interactable to false, so it doesn't show up initially.

Then attach a script to the object you want to click and use OnMouseUp and inside it change the CanvasGroup Alpha to 1 and Interactable to True.

If you're heading for the scripting approach, use OnMouseDown!

boolean isOpen = false;

void OnGUI() //I think this must be used on the camera so you may have to reference a gui controller on the camera
{
  if(isOpen) //Is it Open?
  {
    if(GUI.Button(new Rect(10, 10, 100, 50), "Yes")) //Display and use the Yes button
    {
      Debug.Log("Yes");
      isOpen = false;
    }
    if(GUI.Button(new Rect(110, 10, 100, 50), "No")) //Display and use the No button
    {
      Debug.Log("No");
      isOpen = false;
    }
  }
}

void OnMouseDown() //Get the mouse click
{
  isOpen = true;   //Set the buttons to appear
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM