Unity clicks the button to show/hide the Image method

 (I just provide some examples, don't need to be exactly like me)

Example 1: Making an announcement interface

①Create a button, suggest renaming (easy to distinguish), I changed it to the announcement button

 ②Create an image, and then create a button in the subdirectory of the image. It is also recommended to rename (easy to distinguish), I changed it to image=announcement, button=OK

optimize the layout

Set the On Click () of the announcement button and pay attention to the two ticks

Then set the event of the ''OK'' button

This hook can be selected to be checked or not checked. If checked, it will be displayed after entering. If not checked, you need to click the button to display

renderings

Effect picture 2 (this only needs to adjust the image to the same size as the Canvas)

Example 2 (using a script): making a setting interface

①Add an image, add a button in its subdirectory, and rename it to Settings and Close respectively

optimize the layout

②Add a button and rename it as the setting button

③Create a new script UITips.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UITips : MonoBehaviour
{

    public static Vector3 vec3, pos;
    // Use this for initialization
    void Start()
    {

        gameObject.SetActive(false);
    }

    /// <summary>
    /// 按下鼠标将会触发事件
    /// </summary>
    public void PointerDown()
    {
        vec3 = Input.mousePosition;//获取当前鼠标的位置
        pos = transform.GetComponent<RectTransform>().position;//获取自己所在的位置
    }

    /// <summary>
    /// 鼠标拖拽时候会被触发的事件
    /// </summary>
    public void Drag()
    {
        Vector3 off = Input.mousePosition - vec3;
        //此处Input.mousePosition指鼠标拖拽结束的新位置
        //减去刚才在按下时的位置,刚好就是鼠标拖拽的偏移量
        vec3 = Input.mousePosition;//刷新下鼠标拖拽结束的新位置,用于下次拖拽的计算
        pos = pos + off;//原来image所在的位置自然是要被偏移
        transform.GetComponent<RectTransform>().position = pos;//直接将自己刷新到新坐标
    }

    /// <summary>
    /// 此函数接口将赋予给“弹出对话框”按钮的onClick事件
    /// </summary>
    public void onShow()
    {
        gameObject.SetActive(true);
    }

    /// <summary>
    /// 此函数接口将赋予给“确认”按钮的onClick事件
    /// </summary>
    public void onOK()
    {
        gameObject.SetActive(false);
    }
    // Update is called once per frame
    void Update()
    {

    }
}

Drag the script to the setting (image), and add Event Trigger to the image (click Addcomponent>Event>Event Trigger at the bottom of the image)

In Event Trigger, click Add New Event Type>Pointer Dwon, Add New Event Type>Drag

Set as shown in the figure

Add events to the settings button (button)

Set the close (button) on the settings (image) as shown in the figure

renderings

Example 3: qq group

Guess you like

Origin blog.csdn.net/weixin_57362299/article/details/118343134