Coroutine only works one way
Hey everyone, I have a situation where I have an elevator which moves up and down. I am using a formula to calculate the speed and based on that I want Unity to tell me when the elevator is running and when it is not.
I have two coroutines one for the "lift on" and one for the "lift off".
The problem is everything seems to be working fine when the lift is in its initial state. I do get a message which says the lift is off. Now the lift starts moving and it stops sending me the lift off message and sends me the lift on message. When the lift stops again, it gives me a lift off message.
Now when the elevator goes up I keep getting both lift on and lift off messages which is not suitable since I only need the lift on message now when the elevator is moving.
Here is my code
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
///
/// </summary>
public class LiftAudio : MonoBehaviour
{
float Speed;
float DistanceTravelled;
float initialposition;
private void Start()
{
initialposition = transform.position.y;
}
private void Update()
{
StartCoroutine("LiftSoundOn");
StartCoroutine("LiftSoundOff");
{
//Debug.Log(Speed);
DistanceTravelled = (transform.position.y - initialposition);
initialposition = transform.position.y;
Speed = Mathf.Abs(DistanceTravelled / Time.deltaTime);
}
}
IEnumerator LiftSoundOn()
{
yield return new WaitUntil(LiftOnSpeedReached);
Debug.Log("Lift is on");
}
private bool LiftOnSpeedReached()
{
if (Speed > 3)
{
return true;
}
else
{
return false;
}
}
IEnumerator LiftSoundOff()
{
yield return new WaitUntil(LiftOffSpeedReached);
Debug.Log("Lift is off");
}
private bool LiftOffSpeedReached()
{
if (Speed < 3)
{
return true;
}
else
{
return false;
}
}
}
Answer by Vega4Life · Aug 12, 2019 at 04:10 PM
Essentially you are calling those coroutines 60x a second (or whatever you frame rate is). So that's a lot of coroutines running, thus doing all sorts of things you don't want to have happen.
private void Update()
{
StartCoroutine("LiftSoundOn");
StartCoroutine("LiftSoundOff");
Instead, call those coroutines with an Input or something.
if (Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine("LiftSoundOn");
}
Your answer
Follow this Question
Related Questions
My coroutine won't work 0 Answers
Changing order in layers at runtime with a coroutine 0 Answers
Issue with coroutine 0 Answers
Insantiate Loop Issue 0 Answers
Cinemachine IsBlending and Coroutine 0 Answers