using DG.Tweening; using UnityEngine; public class ReleasableButton : MonoBehaviour { public delegate void OnButtonPressedDelegate(); public event OnButtonPressedDelegate OnButtonPressed; public delegate void OnButtonReleasedDelegate(); public event OnButtonReleasedDelegate OnButtonReleased; public Transform movableParts; public float moveDuration = 0.25f; public float moveAmount = 0.05f; private bool isLocked; private float upPositionY; private float downPositionY; // button state: // 0 - up // 1 - down // 2 - moving private int buttonState; private void Awake() { upPositionY = movableParts.localPosition.y; downPositionY = movableParts.localPosition.y - moveAmount; buttonState = 0; } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } private void OnTriggerEnter(Collider collider) { // if button is up, start moving down if (buttonState == 0 &&!isLocked && collider.gameObject.tag.EndsWith("Hand")) { Activate(); OnButtonPressed?.Invoke(); } } private void OnTriggerExit(Collider collider) { // if button is down, start moving up if (buttonState == 1 && !isLocked && collider.gameObject.tag.EndsWith("Hand")) { Deactivate(); OnButtonReleased?.Invoke(); } } private void Activate() { buttonState = 2; movableParts.DOLocalMoveY(downPositionY, moveDuration).OnComplete(() => { buttonState = 1; }); AudioManager.Instance.PlayAttachedInstance(FMODEvents.Instance.Click, gameObject); } private void Deactivate() { buttonState = 2; movableParts.DOLocalMoveY(upPositionY, moveDuration).OnComplete(() => { buttonState = 0; }); AudioManager.Instance.PlayAttachedInstance(FMODEvents.Instance.Click, gameObject); } public void Lock() { isLocked = true; } public void Unlock() { isLocked = false; } }