我正在使用这个脚本来创建一个npc角色,它将在randm的游戏区域周围运行以设置游戏点数,并且我已经在我的游戏中创建了一个,但是当我尝试使用脚本来创建它时npc在List _patrolPoints中丢失所有方向点,它只会创建坐在那里的多维数据集,因为没有任何方式点而不会移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class navmesh : MonoBehaviour {
[SerializeField]
bool _patrolWaiting;
[SerializeField]
float _totalWaitTime = 3f;
[SerializeField]
float _switchProbability = 0.2f;
[SerializeField]
List<Waypoint> _patrolPoints;
NavMeshAgent _navMeshAgent;
int _currentPatrolIndex;
bool _traveling;
bool _waiting;
bool _patrolFoward;
float _waitTimer;
void Start() {
_navMeshAgent = this.GetComponent<NavMeshAgent>();
_currentPatrolIndex = 0;
SetDestination();
}
void Update() {
_currentPatrolIndex = 0;
SetDestination();
if (_traveling && _navMeshAgent.remainingDistance <= 1.0f) {
_traveling = false;
if (_patrolWaiting) {
_waiting = true;
_waitTimer = 0f;
}
else {
ChangePatrolPoint();
SetDestination();
}
}
if (_waiting) {
_waitTimer += Time.deltaTime;
if (_waitTimer >= _totalWaitTime) {
_waiting = false;
ChangePatrolPoint();
SetDestination();
}
}
}
private void SetDestination() {
if (_patrolPoints != null) {
Vector3 targetVector = _patrolPoints[_currentPatrolIndex].transform.position;
_navMeshAgent.SetDestination(targetVector);
_traveling = true;
}
}
private void ChangePatrolPoint() {
if (UnityEngine.Random.Range(0f, 1f) <= _switchProbability) {
_patrolFoward = !_patrolFoward;
}
if (_patrolFoward) {
_currentPatrolIndex = (_currentPatrolIndex + 1) % _patrolPoints.Count;
}
else {
if (--_currentPatrolIndex < 0) {
_currentPatrolIndex = _patrolPoints.Count - 1;
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPCspawn : MonoBehaviour {
public GameObject NPC;
public Transform NPCspawn1;
public float SpawnRate;
private float SpawnFire;
void Update() {
if (SpawnFire < 20 && Time.time > SpawnFire) {
SpawnFire = Time.time + SpawnRate;
Instantiate(NPC, NPCspawn1.position, NPCspawn1.rotation);
}
}
}
答案 0 :(得分:0)
您用于NPC
属性的对象是预制件吗?如果是这样,它应该保留您在编辑器中为该预制件设置的所有值。
但是,如果您的_patrolpoints
不是预制件的一部分(即。NPC
是您在编辑器中配置的场景内对象),那么您需要申请那些_patrolpoints
手动为每个实例化的副本。
您的代码没有显示_patrolpoints
的设置位置,但对于下面的代码段,我们假设_patrolpoints
是导航网格的公共数组字段(而不是私人名单),
void Update()
{
if (SpawnFire < 20 && Time.time > SpawnFire) {
SpawnFire = Time.time + SpawnRate;
GameObject copy = Instantiate(NPC, NPCspawn1.position, NPCspawn1.rotation);
navmesh nm = copy.GetComponent<navmesh>();
nm._patrolpoints = master_array_of_patrol_points;
}
}