I would like to get a coroutine to move an uncontrolled unit across the screen. I built in some coroutines that wait for 5 seconds and then flip the npc so that the npc is facing the other way.
The routine will do this every 5 seconds, however my unit remains stuck and does not move in the direction I wanted the npc to move in e.g. move right for 5 seconds and move left for 5 seconds.
moverightleft script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveRightLeft : MonoBehaviour
{
public bool isOn;
public bool _isFacingRight;
// Start is called before the first frame update
void Start()
{
_isFacingRight = transform.localScale.x > 0;
InvokeRepeating("MoveRightMoveLeft", 0, 5);
}
// Update is called once per frame
void Update()
{
}
void MoveRightMoveLeft()
{
if (isOn)
{
Debug.Log("ison");
GameObject.Find("SceneHandler").GetComponent<Routines>().startwalkCoroutine(this.gameObject, "right");
if (!_isFacingRight)
Flip();
isOn = false;
} else
{
Debug.Log("isoff");
GameObject.Find("SceneHandler").GetComponent<Routines>().startwalkCoroutine(this.gameObject, "left");
if (_isFacingRight)
Flip();
isOn = true;
}
}
private void Flip()
{
transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
_isFacingRight = transform.localScale.x > 0;
}
}
Routines script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//burrow needed functions from this class
public class Routines : MonoBehaviour
{
public void runCoroutine(IEnumerator coroutine)
{
StartCoroutine(coroutine);
}
public void startwalkCoroutine(GameObject animobj, string direction)
{
StartCoroutine(walkCoroutine(animobj, direction));
}
public void stopwalkCoroutine(GameObject animobj, string direction)
{
StopCoroutine(walkCoroutine(animobj, direction));
}
public IEnumerator walkCoroutine(GameObject animobj, string direction)
{
//while (target > 0)
//{
while (true) {
if (direction == "right")
{
float origposx = animobj.transform.position.x;
float posmovedbyx = origposx + 3;
//target = target + 20;
animobj.transform.position = new Vector3(posmovedbyx, animobj.transform.position.y, animobj.transform.position.z);
//}
} else if (direction == "left")
{
float origposx = animobj.transform.position.x;
float posmovedbyx = origposx - 3;
//target = target + 20;
animobj.transform.position = new Vector3(posmovedbyx, animobj.transform.position.y, animobj.transform.position.z);
//}
}
yield return new WaitForSeconds(1);
}
}
}
#endregion