我试着对5个对象应用同样的协同线,当协同线从游戏的第一阶段开始时,五个对象就会这样做,但是当我让它们从其他类开始时,只有一个对象启动协同线。
这是使5个对象启动协同线的代码:
public class NpcMoveRandomly : MonoBehaviour
{
NavMeshAgent navMeshAgent;
public float timeForNewPath;
public bool inCoroutine;
Vector3 target;
void Start()
{
navMeshAgent = GetComponent<NavMeshAgent>();
}
void Update()
{
if (!inCoroutine)
{
StartCoroutine(MoveRandomly());
}
}
Vector3 getNewRandomPosition()
{
float x = Random.Range(-5, 5);
float z = Random.Range(-5, 5);
Vector3 pos = new Vector3(x, 0 ,z);
return pos;
}
public IEnumerator MoveRandomly()
{
inCoroutine = true;
yield return new WaitForSeconds(timeForNewPath);
GetNewPath();
inCoroutine = false;
}
void GetNewPath()
{
target = getNewRandomPosition();
navMeshAgent.SetDestination(target);
}
}现在,只有一个对象的代码启动协同线(我将只显示它们之间的区别):
//public bool inCoroutine; I changed the inCourotine to startCoroutine but the rest of the code is basicly the same
public bool startCoroutine;
void Update()
{
if (startCoroutine)
{
StartCoroutine(MoveRandomly());
}
}
public IEnumerator MoveRandomly()
{
startCoroutine = false;
...
...
startCoroutine = true;
}在其他班级:
public NpcMoveRandomly npcMoveRandomly;
public void Method()
{
npcMoveRandomly.startCoroutine = true;
}因此,当我使协同线以游戏的lauch开始时,因为inCoroutine默认为false,所以它是可以的,但是当我通过其他类使startCoroutine变为真时,coroutine只适用于1个对象。我真的不知道为什么,也不知道该怎么处理。
发布于 2019-12-10 13:09:23
在场景中创建一个名为NPCManager的游戏对象,并在那里引用所有的npcs。如果它们在开始时已经存在于场景中,只需将它们拖放到编辑器中并放到您的公共数组中:
class NPCManager{
public NpcMoveRandomly[] npcList;
public void Method(){
foreach(NpcMoveRandomly npc in npcList){
npc.startCoroutine = true;
}
}
}或者将NPCManager修改为单个实例,并在将它们安装到这个数组/列表之后直接添加npc……无论如何,有很多方法可以做到这一点。
https://stackoverflow.com/questions/59235157
复制相似问题