我想要一个协程在屏幕上移动一个不受控制的单元。我构建了一些等待 5 秒然后翻转 npc 的协程,使 npc 面向另一个方向。
例程将每 5 秒执行一次,但是我的单元仍然卡住并且没有朝我希望 npc 移动的方向移动,例如向右移动 5 秒,向左移动 5 秒。
moverightleft 脚本
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;
}
}
例程脚本
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