UGUI层级关系,设置事件监听

UGUI层级关系

UGUI的层级关系是通过层次面板的顺序决定的
RectTransfrom组件的方法:
SetAsFirstSibling() :Move the transfrom to the start of the local transfrom list.最底层
SetAsLastSibling()::Move the transfrom to the end of the local transfrom list.最顶层
SetSiblingIndex():Set the sibling index.指定层
GetSiblingIndex():Get the sibling index.获得指定层索引

事件监听

方法一:通过代码添加监听事件

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Script_2 : MonoBehaviour {
    Button button;
    // Use this for initialization
    void Start () {
        button = GameObject.Find("Button").GetComponent<Button>();
        button.onClick.AddListener(OnButtonClick);
    }
    void OnButtonClick()
    {
        Debug.Log("onbuttonclick");
    }
    // Update is called once per frame
    void Update () {
       
    }
}

方法二:通过代码和inspector面板添加监听事件

image.png
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Script_3 : MonoBehaviour {

    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update ()
    {
        
    }
    public void OnButtonClick()
    {
        Debug.Log("button click");
    }
}

例子:通过button的点击事件修改层级关系

采用方法二

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

public class Script_3 : MonoBehaviour {
    public Image imageA;
    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update ()
    {
        
    }
    public void OnButtonClick()
    {
        Debug.Log("button click");
        if (imageA != null)
        {
            RectTransform rtf = imageA.rectTransform;
            rtf.SetAsFirstSibling();
        }
    }
}
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。