Hello,
I am making a script for my character so that he automatically moves to a certain point in my scene.
Thing is, he keeps trying to get to the target position, even after already reaching it. I start my coroutine by saying if it has been used before (default set as false in the Start function), and set it to true once the coroutine is being used.
My thoughts were that it shouldn’t be possible to call it (therefore not moving the character), unless CoroutineUsed = false;? Is it something I’m just overlooking, or something I’m missing entirely?
I thought of using if(transform.position == target.position){
StopCoroutine(“MoveTowardsPoint”), but that would obviously just pull my character back the moment he moved away…
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(PlayerController))]
public class CutsceneWalking : MonoBehaviour {
//Variables----------------------------
public Transform target;
public float speed;
public Animator anim;
private bool CoroutineUsed;
//-------------------------------------
private void Start()
{
CoroutineUsed = false;
}
void FixedUpdate()
{
if (CoroutineUsed == false)
{
StartCoroutine("MoveTowardsPoint");
}
if(CoroutineUsed == true)
{
StopCoroutine("MoveTowardsPoint");
}
}
IEnumerator MoveTowardsPoint()
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
CoroutineUsed = true;
anim.SetBool("IsWalking", true);
yield return null;
}
}
Could anyone shed some light on my weird scripting here? (and by that I don’t mean “Give me the answer/fix”. I mean “Please give me some hints which might get me to the answer”)