Unity3DUIマスクとポップアップウィンドウ

詳細な説明は少し長く、画像とリソースのすぐ上にある場合があります(実装の特定の手順については以下を参照してください)

GIF画像は少し動かなくなっているように見えますが、スムーズに実行されます。

コードクラウド:https//gitee.com/NCAA_admin/Alert.git

特定の実装手順

1.背景画像の背景を作成し、対応する属性値を設定します

2.キャンバスのプロパティとゲームウィンドウの比率を設定します

3. AlertImageという名前のポップアップマスクマスクを作成します。パラメータは次のように設定されます。

4.アラートの下にメッセージイメージという名前のポップアップメッセージボックスを作成し、次のようにパラメータを設定します

5.メッセージの下にテキストオブジェクトテキストを作成し、次のようにパラメータを設定します

6.次に、[アラート]の下に[確認]と[キャンセル]の2つのボタンを作成します

7.2つのボタンのテキストパラメータは次のとおりです。

8. Shaderマスクを作成し、Assetsの下にShadersフォルダーを作成し、Shadersフォルダーの下にBlurという名前のShaderスクリプトを作成します。

10. Shaderスクリプト、内容は次のとおりです(Shaderの実現原理と手順については、トピック分析を行う時間があります)

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "Custom/Blur"
{
	// 属性
	Properties
	{
		// 定义 1-255 范围的半径 默认 1
		_Radius("Radius", Range(1, 255)) = 1
	}

	Category
	{
		Tags{ "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Opaque" }

		SubShader
	{

	GrabPass
	{
		Tags{ "LightMode" = "Always" }
	}

	Pass
	{
		Tags{ "LightMode" = "Always" }
		
		CGPROGRAM
		#pragma vertex vert
		#pragma fragment frag
		#pragma fragmentoption ARB_precision_hint_fastest
		#include "UnityCG.cginc"

	struct appdata_t
	{
		float4 vertex : POSITION;
		float2 texcoord: TEXCOORD0;
	};

	struct v2f
	{
		float4 vertex : POSITION;
		float4 uvgrab : TEXCOORD0;
	};

	v2f vert(appdata_t v)
	{
		v2f o;
		o.vertex = UnityObjectToClipPos(v.vertex);
#if UNITY_UV_STARTS_AT_TOP
		float scale = -1.0;
#else
		float scale = 1.0;
#endif
		o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y*scale) + o.vertex.w) * 0.5;
		o.uvgrab.zw = o.vertex.zw;
		return o;
	}

	sampler2D _GrabTexture;
	float4 _GrabTexture_TexelSize;
	float _Radius;

	half4 frag(v2f i) : COLOR
	{
		half4 sum = half4(0,0,0,0);

#define GRABXYPIXEL(kernelx, kernely) tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(float4(i.uvgrab.x + _GrabTexture_TexelSize.x * kernelx, i.uvgrab.y + _GrabTexture_TexelSize.y * kernely, i.uvgrab.z, i.uvgrab.w)))

		sum += GRABXYPIXEL(0.0, 0.0);
		int measurments = 1;

		for (float range = 0.1f; range <= _Radius; range += 0.1f)
		{
			sum += GRABXYPIXEL(range, range);
			sum += GRABXYPIXEL(range, -range);
			sum += GRABXYPIXEL(-range, range);
			sum += GRABXYPIXEL(-range, -range);
			measurments += 4;
		}

		return sum / measurments;
	}
		ENDCG
	}
		GrabPass
	{
		Tags{ "LightMode" = "Always" }
	}

		Pass
	{
		Tags{ "LightMode" = "Always" }

		CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
#include "UnityCG.cginc"

		struct appdata_t
	{
		float4 vertex : POSITION;
		float2 texcoord: TEXCOORD0;
	};

	struct v2f
	{
		float4 vertex : POSITION;
		float4 uvgrab : TEXCOORD0;
	};

	v2f vert(appdata_t v)
	{
		v2f o;
		o.vertex = UnityObjectToClipPos(v.vertex);
#if UNITY_UV_STARTS_AT_TOP
		float scale = -1.0;
#else
		float scale = 1.0;
#endif
		o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y*scale) + o.vertex.w) * 0.5;
		o.uvgrab.zw = o.vertex.zw;
		return o;
	}

	sampler2D _GrabTexture;
	float4 _GrabTexture_TexelSize;
	float _Radius;

	half4 frag(v2f i) : COLOR
	{

		half4 sum = half4(0,0,0,0);
		float radius = 1.41421356237 * _Radius;

#define GRABXYPIXEL(kernelx, kernely) tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(float4(i.uvgrab.x + _GrabTexture_TexelSize.x * kernelx, i.uvgrab.y + _GrabTexture_TexelSize.y * kernely, i.uvgrab.z, i.uvgrab.w)))

		sum += GRABXYPIXEL(0.0, 0.0);
		int measurments = 1;

		for (float range = 1.41421356237f; range <= radius * 1.41; range += 1.41421356237f)
		{
			sum += GRABXYPIXEL(range, 0);
			sum += GRABXYPIXEL(-range, 0);
			sum += GRABXYPIXEL(0, range);
			sum += GRABXYPIXEL(0, -range);
			measurments += 4;
		}

		return sum / measurments;
	}
		ENDCG
	}
	}
	}
}

11. Assetsの下にMaterialsという名前のフォルダーを作成し、Materialsフォルダーの下にMaskBlurという名前のMaterialマテリアルを作成します。

12. [アラート]でMaskBlurマテリアルを指定し、マテリアルのブラー値を5に設定します

13.インタラクティブ効果に過度のアニメーション感を持たせるには、エディター上部のメニューバーにある[Windows]> [アセットストア]でアセットストアを開きます。

14. DoTweenキーワードを検索し、ダウンロードを入力します

15.ダウンロードが完了したら、[インポート]をクリックします

16. Assetsの下にScriptsフォルダーを作成し、Scriptsの下にAlert.csスクリプトを作成します

17.Alert.csスクリプトの内容

using UnityEngine;
using DG.Tweening;
using UnityEngine.UI;
using UnityEngine.EventSystems;
//显示Alert会话
public class Alert : MonoBehaviour
{
    public static Alert Instance;
    private void Awake()
    {
        Instance = this;
    }
    [Tooltip("会话对象")] public RectTransform m_alert;
    //获取ui blur(alert)初始大小
    private Vector2 _uiBlurSize;
    //获取ui blur(alert)初始scale
    private Vector2 _uiBlurScale;
    //透明遮罩层
    private RectTransform _transparentMask;
    //透明遮罩层的初始颜色值值
    private Color _transparentMaskColor;
    //获取confirm
    private RectTransform _confirm;
    //获取confirm初始大小
    private Vector2 _confirmSize;
    //获取confirm初始scale
    private Vector2 _confirmScale;
    //获取text对象
    private Text _text;
    //获取text的大小
    private Vector2 _textSize;
    //获取text scale
    private Vector2 _textScale;
    void Start()
    {
        //判断并且赋值
        if (!m_alert)
        {
            m_alert = transform.GetComponent<RectTransform>();
        }
        //获取uiblur(alert)初始大小
        _uiBlurSize = m_alert.rect.size;
        _uiBlurScale = m_alert.localScale;
        //获取透明遮罩层
        _transparentMask = m_alert.GetChild(0).GetComponent<RectTransform>();
        //透明遮罩层的颜色
        _transparentMaskColor = _transparentMask.GetComponent<Image>().color;
        //获取confirm
        _confirm = m_alert.GetChild(1).GetComponent<RectTransform>();
        //获取confirm初始大小
        _confirmSize = _confirm.rect.size;
        _confirmScale = _confirm.localScale;
        //获取text对象
        _text = _confirm.GetChild(0).GetComponent<Text>();
        //获取text的大小
        _textSize = _text.GetComponent<RectTransform>().rect.size;
        _textScale = _text.rectTransform.localScale;
        //确定取消按钮
        _Confirm();
        _Cancel();
        //初始设置隐藏
        if (m_hideOnStart)
            _SetHideImmediate();
    }

    /// <summary>
    /// 无动画立即隐藏
    /// </summary>
    public void _SetHideImmediate()
    {
        //设置隐藏
        m_alert.gameObject.SetActive(false);
        _confirm.gameObject.SetActive(false);
        _text.gameObject.SetActive(false);
        _transparentMask.gameObject.SetActive(false);
        //宽高设置0
        m_alert.DOScale(Vector3.zero, 0);
        _confirm.DOScale(Vector3.zero, 0);
        //设置遮罩层alpha = 0
        _transparentMask.GetComponent<Image>().DOFade(0, 0);
    }
    /// <summary>
    /// 开始时为隐藏状态
    /// </summary>
    [Tooltip("开始时为隐藏状态")]
    public bool m_hideOnStart = true;
    /// <summary>
    /// 隐藏
    /// </summary>
    public void _SetHide()
    {
        //设置隐藏
        _text.gameObject.SetActive(false);
        //宽高设置0
        m_alert.DOScale(Vector2.zero, _SetShow_duration)
            .onComplete = () =>
            {
                m_alert.gameObject.SetActive(false);
            };
        _confirm.DOScale(Vector2.zero, _SetShow_duration)
            .onComplete = () =>
            {
                _confirm.gameObject.SetActive(false);
            };
        //隐藏透明遮罩层
        _transparentMask.GetComponent<Image>().DOFade(0, _SetShow_duration)
            .onComplete = () =>
            {
                _transparentMask.gameObject.SetActive(false);
            };
    }
    /// <summary>
    /// 显示
    /// </summary>
    public void _SetShow()
    {
        //设置显示
        m_alert.gameObject.SetActive(true);
        _confirm.gameObject.SetActive(true);
        _transparentMask.gameObject.SetActive(true);
        //宽高设置成初始大小+5%再回到原来的大小
        m_alert.DOScale(_uiBlurScale + _uiBlurScale * 0.05f, _SetShow_duration)
            .onComplete = () =>
            {
                //完成后回到初始大小 时间为原来的1/5
                m_alert.DOScale(_uiBlurScale, _SetShow_duration / 5f);
            };
        _confirm.DOScale(_confirmScale + _confirmScale * 0.05f, _SetShow_duration)
            .onComplete = () =>
            {
                //完成后回到初始大小 时间为原来的1/5
                _confirm.DOScale(_confirmScale, _SetShow_duration / 5f);
                //并且显示text
                _text.gameObject.SetActive(true);
            };
        //显示透明遮罩层
        _transparentMask.GetComponent<Image>().DOFade(_transparentMaskColor.a, _SetShow_duration);
    }
    /// <summary>
    /// 显示动画时间
    /// </summary>
    private float _SetShow_duration = 0.3f;

    /// <summary>
    /// 按钮的hover效果
    /// </summary>
    /// <param name="button">按钮</param>
    public void _OnHover(Transform button)
    {
        if (!m_inited)
        {
            m_inited = true;
            //获取初始大小
            m_initialScale = transform.GetComponent<RectTransform>().localScale.x;
        }
        if (!button.GetComponent<EventTrigger>()) button.gameObject.AddComponent<EventTrigger>();
        EventTrigger trigger = button.GetComponent<EventTrigger>();
        EventTrigger.Entry entry = new EventTrigger.Entry();
        entry.eventID = EventTriggerType.PointerEnter;
        entry.callback = new EventTrigger.TriggerEvent();
        entry.callback.AddListener(delegate (BaseEventData baseEvent) {
            button.GetComponent<RectTransform>().DOScale(m_localScale, 0.3f);
        });
        trigger.triggers.Add(entry);

        EventTrigger.Entry entry2 = new EventTrigger.Entry();
        entry2.eventID = EventTriggerType.PointerExit;
        entry2.callback = new EventTrigger.TriggerEvent();
        entry2.callback.AddListener(delegate (BaseEventData baseEvent) {
            button.GetComponent<RectTransform>().DOScale(m_initialScale, 0.3f);
        });
        trigger.triggers.Add(entry2);
    }
    /// <summary>
    /// 变大尺度默认1
    /// </summary>
    [Tooltip("变大尺度默认1.2f")]
    public float m_localScale = 1.2f;
    /// <summary>
    /// 初始的大小
    /// </summary>
    private float m_initialScale;
    /// <summary>
    /// 是否被初始化
    /// </summary>
    private bool m_inited = false;

    /// <summary>
    /// 确定
    /// </summary>
    public void _Confirm()
    {
        _OnHover(m_confirm);
        m_confirm.GetComponent<Button>().onClick.AddListener(delegate {
            _SetHide();
        });
    }
    /// <summary>
    /// 确定按钮
    /// </summary>
    [Tooltip("确定按钮")]
    public Transform m_confirm;
    /// <summary>
    /// 取消按钮
    /// </summary>
    public void _Cancel()
    {
        _OnHover(m_cancel);
        m_cancel.GetComponent<Button>().onClick.AddListener(delegate {
            _SetHide();
        });
    }
    [Tooltip("取消按钮")]
    public Transform m_cancel;

}

18. Alert.csスクリプトをAlertオブジェクトにドラッグし、ConfirmオブジェクトとCancelオブジェクトをAlertの対応するコンポーネントにドラッグします。

19.次に、Assets> Scriptsフォルダーの下に新しいキーボードイベントスクリプトKeyEvent.csを作成します。

20.KeyEvent.csスクリプトの内容

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

public class KeyEvent : MonoBehaviour
{
    /// <summary>
    /// 获取Alert组件
    /// </summary>
    private Alert alert;
    void Start()
    {
        //实例化组件
        alert = Alert.Instance;
    }

    void Update()
    {
        //键盘事件
        _KeyDown();
    }

    /// <summary>
    /// 按下键盘执行
    /// </summary>
    public void _KeyDown()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            alert._SetShow();
        }
    }

}

21.階層の下にスクリプトマネージャーの新しい空のオブジェクトスクリプトを作成し、それにKeyEvent.csスクリプトを添付します

22.階層の下のコンポーネントの階層をより明確にするために、次のように3つの新しい空のオブジェクトがそれぞれ作成されました。

23.最後にゲームを実行し、Escキーを押してメッセージボックスをポップアップします

終了:GIFレンダリングについては、記事の上部をご覧ください。

おすすめ

転載: blog.csdn.net/zhunju0089/article/details/103463582