Best way to move this code to the Update function?

Hello,I am using Vector3.MoveTowards in this code, and it does work, but the movement is instant instead of updating each frame. I researched that the way to fix this was to put it in the update function. However. I’m not sure how to do this if I need to have an if statement in another function which determines which movement I should use?

Another question, which forum is the best for others to critique your code? I think it’s the Documentation forum but I’m not sure.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IEOMovement : MonoBehaviour
{
    public GameObject IEO;
    [Range(0f, 1f)]
    public float spawnChance = 0.5f;
    [Range(0f, 15f)]
    public float speed = 10f;
    public GameObject LeftScreenPoint;
    public GameObject RightScreenPoint;
    private float minSpawnTime = 5f;
    private float maxSpawnTime = 15f;

    void Update ()
    {
      //How do I move leftToRightMovement(); to here, if I need to have an if statement in another function which determines which movement I should use? 
    }
    void Start()
    {
        StartCoroutine(Spawn());
    }
    private IEnumerator Spawn()
    {
      
        if (Random.value < spawnChance)
        {
          
            if ((gameObject).CompareTag("leftIEO"))
            {
                leftToRightMovement();
            }
            else
            {
                rightToLeftMovement();
            }
            // Setup for next spawn
            yield return new WaitForSeconds(Random.Range(minSpawnTime, maxSpawnTime));
            StartCoroutine(Spawn());
        }
    }
    void leftToRightMovement()
    {
        //place the gameObject prefab at the LeftScreenPoint's position
        //Instantiate(IEO, LeftScreenPoint.transform.position, LeftScreenPoint.transform.rotation);
        IEO.transform.position = LeftScreenPoint.transform.position;
        //moves object to the RightScreenPoint
        IEO.transform.position = Vector3.MoveTowards(IEO.transform.position, RightScreenPoint.transform.position, (speed * Time.deltaTime));
    }
}

Right now you’re only calling leftToRightMovement() from within the Spawn() coroutine. This would mean movement only occurs on the specific frame Spawn() runs. I’m not sure exactly what you are going for. If it just to get leftToRightMovement() called every frame, just remove it from Spawn() and call it in Update(). If your issue is that all needed movement is completing in a single frame, then you likely have your “speed” variable set way too high.

Hello and thank you! Your answer worked! This was actually a shorter version of the code I had, but. I was able to make it work, and found that there are a lot of unessacery things in my code I will remove. Thanks again!

1 Like