Problem with Lerp Function not running

G’Day, So I have a section of code that partly runs with a collision trigger. The if statement runs (as noted in the Debug.Log). However, it seems that the ‘LerpFunction’ doesn’t run (not Debug entry from LerpFunction).

The purpose of the script is too slow down the target (hit) animal to a stop before destroying it (and changing the animation state. My animal motion is in another script, which has different speeds set for each animal type, hence my decision to just change the speed to 0 over time.

see what you think.

BrBarry.

public class DetectCollisions : MonoBehaviour
{
    private AudioSource audioSource;
    public AudioClip deathFX;
    public float deathTime = 0f;
    private float currentSpeed;
    private GameObject targetAnimal;

    private void Awake()
    {
        audioSource = GetComponent<AudioSource>();
    }

    public void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Pizza") {
            ScoreBoard.feedCount+= 1;

            targetAnimal = this.gameObject;

            audioSource.PlayOneShot(deathFX);

            currentSpeed = targetAnimal.GetComponent<MoveForward>().speed;

            Debug.Log("Animal Current Speed was " + currentSpeed);
           
            LerpFunction(currentSpeed);

            targetAnimal.GetComponent<Animator>().SetFloat("Speed_f", 0f);
            targetAnimal.GetComponent<Animator>().SetBool("Eat_b", true);
       
        }

        Destroy(gameObject, deathTime);
        //Destroy(other.gameObject);
    }

    IEnumerator LerpFunction(float startSpeed)
    {
        float timeStarted = 0;
        float duration = 2;

        Debug.Log("this did run?");

        while (timeStarted <= duration)
        {
            targetAnimal.GetComponent<MoveForward>().speed = Mathf.Lerp(startSpeed, 0, timeStarted / duration);

            yield return null;

            timeStarted += Time.deltaTime;
        }
    }

}

You have to call coroutines with the StartCoroutine() method.

Line 27 should be

StartCoroutine(LerpFunction(currentSpeed));
1 Like

Massive thanks. Yeah, I did see a couple of examples around, but most had the StartCoroutine() in the Start function, which made no sense to me and didn’t work/created other errors. So I left it out not knowing how it should actually be applied.

1 Like

No problem, good luck with your project.