我的场景中有几个滑块,我试图通过按下按钮来重置。我不确定如何引用Slider组件的value字段。
允许使用GUI按钮重置的最终编辑(感谢大家的帮助和指导):
public class buttonreset : MonoBehaviour
{
public Button button1;
Slider[] sliders;
void Start()
{
button1.onClick.AddListener(() => buttonCallBack(button1));
//Find Sliders
sliders = FindObjectsOfType<Slider>() as Slider[];
}
private void buttonCallBack(Button buttonPressed)
{
{
if (buttonPressed == button1)
{
for (int i = 0; i < sliders.Length; i++)
sliders[i].value = 0;
Debug.Log("Clicked: " + button1.name);
}
}
}
void OnDisable()
{
//Un-Register Button Events
button1.onClick.RemoveAllListeners();
}
}
使用@PassetCronUs的新代码再次编辑:
public class buttonreset : MonoBehaviour
{
Slider[] sliders;
void Start()
{
//Find Sliders
sliders = FindObjectsOfType<Slider>() as Slider[];
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//Loop thrpugh sliders and reset them
for (int i = 0; i < sliders.Length; i++)
sliders[i].value = 0;
}
}
}
使用新脚本编辑(它重置了层次结构中的第一个滑块):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class buttonsave : MonoBehaviour
{
private Slider[] slider;
void Awake()
{
slider = GameObject.FindGameObjectWithTag("slider").GetComponents<Slider>();
}
void OnGUI()
{
for (int i = 0; i < slider.Length; ++i)
{
if (Input.GetMouseButtonDown(0))
{
slider[i].value = 0;
}
}
}
}
旧脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class buttonreset : MonoBehaviour {
void Start()
{
slidertoreset = GameObject.FindGameObjectWithTag("slider").GetComponents<Slider>();
}
void OnGUI()
{
if (Input.GetMouseButtonUp(0))
{
Slider.value = 0;
}
}
}
寻求帮助,谢谢。
答案 0 :(得分:1)
使用Sliders
查找所有FindObjectsOfType
组件,将它们存储在一个数组中,然后循环显示它们,并在单击鼠标按钮时将其重置。
Slider[] sliders;
void Start()
{
//Find Sliders
sliders = FindObjectsOfType<Slider>() as Slider[];
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//Loop thrpugh sliders and reset them
for (int i = 0; i < sliders.Length; i++)
sliders[i].value = 0;
}
}
请勿使用OnGUI
功能。那用于旧的UI系统。 Update
函数适用于此。