- Home /
CancelInvoke cant cancell,Updating InvokeRepeating
I don't understand what I am doing wrong, and why, but when I do CancelInvoke inside Update, its still executing, i can still hear the audio, and transformations.
using UnityEngine;
using Random = UnityEngine.Random;
public class TelephoneBooth : MonoBehaviour
{
public AudioClip ringSound;
public AudioSource source;
public bool _isOpen;
void Start()
{
//Open();
}
private void Update()
{
if (_isOpen && !IsInvoking("Open"))
{
Invoke ("Open", 3);
Debug.Log("Invoked");
}
if (!_isOpen && IsInvoking("Open"))
{
CancelInvoke ("Open");
Debug.Log("CANCEL");
}
}
void Open()
{
InvokeRepeating("Ring", 0, 3.0f);
InvokeRepeating("ShakeThePhone", 0, 0.1f);
}
void Ring()
{
source.PlayOneShot(ringSound);
}
void ShakeThePhone()
{
transform.localScale = new Vector2(1f, Random.Range(0.1f, 0.3f)+1f );
}
}
Answer by swanne · Nov 02, 2021 at 03:12 PM
Hi, I think it might be because you are not specifically cancelling the invoke of Ring and ShakeThePhone. The Open method is cancelled but there's not a distinct cancel of the other methods. Try replacing CancelInvoke("Open"); with CancelInvoke(); This will cancel all invoked methods.
Yes, that helped. BTW, its not too much, putting in Update? Like a normal Coroutine would be better?
Great!
You're doing the checking for open correctly by having it the Update function. Unless you want to check at slower intervals? Then a coroutine could be used for that? However, the change I would make is to Invoke Open. As this function invokes 2 functions that you want repeating, you dont need to keep invoking this one. I would just call the Open function if _isOpen && !IsInvoking("Ring");