(Solved) Lerp not working, object not moving on contact of trigger.

This is the first part of the code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/* 
*  This code is for objects to be pushed by player object.
*  for falling we use FallCheck script for these objects
*  This script just moves the object on X and Z axis if player "pushes" it
* 
*  Each child has its on script that sends a "signal" to this script if player is "pushing" it
*/

public class PushableObject : MonoBehaviour
{
    bool moving = false;

    public int moveSpeed = 5;

    public void PushObject(GameObject collider)
    {
        if (!moving) // Make sure game object is not already moving
        {
            moving = true;

            switch (collider.name)
            {
                case "xTop":
                    initiateMovablePush(1, 0);
                    break;
                case "xBottom":
                    initiateMovablePush(-1, 0);
                    break;
                case "zTop":
                    initiateMovablePush(0, 1);
                    break;
                case "zBottom":
                    initiateMovablePush(0, -1);
                    break;
                default:
                    Debug.Log("collider.name");
                    break;
            }
        }
    }

    IEnumerator initiateMovablePush(int x, int z) // Same script as fallCheck just going different direction
    {
        Debug.Log("PushObject");
        Vector3 currentPos = gameObject.transform.position;
        Vector3 newPosition = new Vector3(gameObject.transform.position.x + x, gameObject.transform.position.y, gameObject.transform.position.z + z);
        var t = 0f;
        while (t < 1)
        {
            t += Time.deltaTime / moveSpeed;
            gameObject.transform.position = Vector3.Lerp(currentPos, newPosition, t);
            yield return null;
        }
        moving = false;
    }
}

This is the part that calls is

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ColliderPushable : MonoBehaviour
{
    public PushableObject PushableObject;

    void OnTriggerEnter(Collider other)
    {
        PushableObject.PushObject(gameObject);
    }
}

The game object is not being moved and no Debug.Logs are being shown in the console. I dont know what I am doing wrong, here are pictures of the scene


Each of the “triggers” are the rectangular parts on the box

Thank you in advance. I am most likely making a really small/dumb mistake but I have tried almost everything to figure out the reason.

Since you are using an “IEnumerator” you have to call it as following:

StartCoroutine(initiateMovablePush(1, 0));

Since you need to start the Enumerator somehow :slight_smile:

I knew I was making some dumb mistake, thank you!

1 Like