-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDoTweenToggle.cs
More file actions
53 lines (44 loc) · 1.53 KB
/
DoTweenToggle.cs
File metadata and controls
53 lines (44 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
public class DoTweenToggle : MonoBehaviour
{
public RectTransform handle; // The circular knob
public Image background; // The background (oval shape)
public Color onColor = new Color(0.2f, 0.5f, 1f); // Active state color
public Color offColor = new Color(0.8f, 0.8f, 0.8f); // Inactive state color
public float toggleDuration = 0.3f; // Animation duration
private Toggle toggle;
private Vector2 offPosition;
private Vector2 onPosition;
void Start()
{
toggle = GetComponent<Toggle>();
// Calculate knob positions
offPosition = handle.anchoredPosition;
onPosition = new Vector2(-offPosition.x, offPosition.y);
// Add listener to the toggle
toggle.onValueChanged.AddListener(OnToggleChanged);
// Initialize the toggle state
UpdateToggle(toggle.isOn, true);
}
void OnToggleChanged(bool isOn)
{
UpdateToggle(isOn, false);
}
void UpdateToggle(bool isOn, bool instant)
{
// Animate background color
background.DOColor(isOn ? onColor : offColor, toggleDuration);
// Animate the knob position
Vector2 targetPosition = isOn ? onPosition : offPosition;
if (instant)
{
handle.anchoredPosition = targetPosition;
}
else
{
handle.DOAnchorPos(targetPosition, toggleDuration).SetEase(Ease.OutQuad);
}
}
}