Hello, this is driving me crazy trying to google a solution.
I’m wanting a delay between these two events within the single click of a button.
The two events closes one canvas (canvas this button is inside) then opens a new canvas.
I want a delay before the next canvas opens so that the camera movement is completed before the canvas opens.
The code below moves my camera
function MM_CameraPosUpgrade()
{
GameObject.Find("Camera").GetComponent.<Transform>().DOMove(Vector3(2.90, 3.69, 10.35),1.5, false);
}
I’ve figured it out using the free assest store tween library DOTween.
What I want to happen: Click Button → Camera Moves to New position → current active canvas is hidden → New canvas is visible
All of this happens with one click.
I dont want the new canvas to open untill the camera has moved to it’s new position.
My Code looks like this
var upgrade: GameObject;
function MM_CameraPosUpgrade()
{
GameObject.Find("Camera").GetComponent.<Transform>().DOMove(Vector3(2.90, 3.69, 10.35),1.5, false).OnComplete(off);
}
function off()
{
gameObject.SetActive(false);
upgrade.SetActive(true);
}
The canvas is stored in var upgrade. I use DOTween API ‘DoMove’ to move the camera on button click. Then i use another API ‘OnComplete’ to call another function i’ve made that will only start once the camera has finished moving.
with DOTween I did see other API where you can delay with specific times in mind, i just needed to start an event when camera finished moving.
if anyone needs help with delaying inside an OnClick then let me know.
You can make the OnClick() function call a function that calls a coroutine. Inside the coroutine you can make one event happen then add a delay, and then make the other event happen after the delay.
Just so happens that I already had something laying around that could do this- ripped most of it out for simplicity, but this should do what you want:
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
[RequireComponent(typeof(Button))]
public class DelayedOnClick : MonoBehaviour
{
[SerializeField, Range(.01f, 3f)]
private float _delay = .01f;
[SerializeField, Space(10f)]
private UnityEvent _onClick;
private Button _thisButton;
private WaitForSeconds _delayTimer;
private void Awake()
{
_thisButton = GetComponent<Button>();
// cache the yield instruction for performance
_delayTimer = new WaitForSeconds(_delay);
}
private void Start()
{
// get alerted when the button is pressed
_thisButton.onClick.AddListener(() => StartCoroutine(DelayedClickRoutine()));
}
private IEnumerator DelayedClickRoutine()
{
// wait the delay time, then invoke the event
yield return _delayTimer;
_onClick.Invoke();
}
}