Unity开发_滑动Toggle按钮
using UnityEngine;
using UnityEngine.UI;
public class TAGButton : MonoBehaviour
{
public Color IsLaft;
public Color IsRight;
Toggle _rootToggle;
Transform _handle;
Image _backGround;
float _distance;
float _moveTime;
private void Awake()
{
_rootToggle = this.GetComponent<Toggle>();
_backGround = this.GetComponent<Image>();
_handle = this.transform.GetChild(0);
_distance = this.GetComponent<RectTransform>().rect.width / 4;
_rootToggle.isOn = false;
_moveTime = 0.06f;
}
// Update is called once per frame
void Update()
{
if (Mathf.Abs(_handle.localPosition.x) - _distance < 0.1f)
{
MoveIng();
}
else
{
MoveEnd();
}
}
void MoveIng()
{
_backGround.color = Color.Lerp(_backGround.color, _rootToggle.isOn ? IsRight : IsLaft, _moveTime);
_handle.localPosition = Vector2.Lerp(_handle.localPosition, new Vector2(_rootToggle.isOn ? _distance : -_distance, _handle.localPosition.y), _moveTime);
}
void MoveEnd()
{
_backGround.color = _rootToggle.isOn ? IsRight : IsLaft;
_handle.localPosition = new Vector2(_rootToggle.isOn ? _distance : -_distance, _handle.localPosition.y);
}
}