天天看点

unity uGui绑定事件

Button

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

public class LearnUIButton : MonoBehaviour
{
    public Button button;
    public void Awake()
    {
        button.onClick.AddListener(OnButtonClick);
    }


    public void OnButtonClick()
    {
        Debug.Log("按钮被点击了");
    }

}

           

Toggle

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

public class LearnToggle : MonoBehaviour
{
    public Toggle toggle;
    public void Awake()
    {
        toggle.onValueChanged.AddListener((this.OnToggleValueChange));
    }
    public void OnToggleValueChange(bool isOn)
    {
        Debug.Log("ToggleisOn:" + isOn);
    }
}

           

Slider

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

public class LearnSlider : MonoBehaviour
{
    // Start is called before the first frame update
    public Slider slider;
    public void Awake()
    {
        slider.onValueChanged.AddListener(this.OnSlideValueChanged);
    }
    public void OnSlideValueChanged(float f)
    {
        Debug.Log("slideValue:" + f);

    }

}

           

Dropdown

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

public class LearnDropdown : MonoBehaviour
{
    public Dropdown dropdown;
    public void Awake()
    {
        dropdown.onValueChanged.AddListener(this.OnValueChanged);
    }
    public void OnValueChanged(int value) {
        Debug.Log("DropdownValue:" + value);
    }

}

           

Scrollbar

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

public class LearnScrollBar : MonoBehaviour
{
    public Scrollbar scrollbar;
    public void Awake()
    {
        scrollbar.onValueChanged.AddListener(this.OnValueChanged);
    }
    public void OnValueChanged(float f)
    {
        Debug.Log("srcollBarValue:" + f);
    }

}

           

为每个UI分别添加C#脚本,然后每个ui比如dropdown绑定代码中

public Dropdown dropdown

unity uGui绑定事件

然后play

分别操作相应控件,控制台就会打印出相应信息

如下

unity uGui绑定事件