我正在尝试通过鼠标单击导航网格来生成士兵并将他们作为一个团移动。但我收到“只能在活动代理上调用“设置目标”错误。我在论坛中读到,这可能是由于从导航网格实例化到高或低造成的。但是无论我将生成点放在 y 轴上的哪个位置,都没有任何变化。我通常在 Y = 0 上生成它们似乎 Unity 在实例化时将我的预制克隆自动设置为 y = 0.303……我不知道为什么。我无法在场景视图中运行时在 y 轴上平移士兵。发生的另一个“有趣”的事情是,即使我在 Awake 上调用 getComponent,我也会为导航网格代理获得一个未分配的引用异常。我必须在一个单独的函数中调用它以使其分别工作以到达“设置目标”错误。
public class Move : MonoBehaviour
{
private Ray _ray;
private RaycastHit hit;
private float raycastLength = 1000.0f;
private UnitMove nav;
public static List<GameObject> selectedUnits = new List<GameObject>();
void Update ()
{
_ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(_ray, out hit, raycastLength))
{
MoveRegiment(hit.point);
}
}
}
void MoveRegiment(Vector3 moveToPos)
{
foreach (GameObject go in selectedUnits)
{
nav = go.GetComponent<UnitMove>();
nav.setNav();
nav.MovetoNav(moveToPos.x, moveToPos.y, moveToPos.z);
}
}
}
public class UnitMove : MonoBehaviour
{
private NavMeshAgent nav;
public int xPos { get; set; }
public int yPos { get; set; }
void Awake()
{
nav = GetComponent<NavMeshAgent>(); //does not work...
}
public void setNav()
{
nav = GetComponent<NavMeshAgent>();
}
public void MovetoNav(float x, float y, float z)
{
nav.SetDestination(new Vector3(x , y, z));
}
}
public class RegimentSpwan : MonoBehaviour
{
public Text row;
public Text unitAmmount;
public GameObject Unit;
private GameObject _newGO;
private Vector3 pos;
public void OnclickNewRegiment()
{
DestroyImmediate(GameObject.Find("Regiment"));
_newGO = new GameObject("Regiment");
Instantiate(_newGO, this.transform.position, Quaternion.identity);
for (int i = 0; i < Convert.ToInt16(row.text); i++)
{
for (int j = 0; j < Convert.ToInt16(unitAmmount.text); j++)
{
Debug.Log(this.transform.position.y); //is zero
Unit.name = "Unit_" + i + "_" + j;
pos = new Vector3(this.transform.position.x + j * 2,this.transform.position.y, this.transform.position.z + i * 2);
Instantiate(Unit, pos, Quaternion.identity, _newGO.transform);
Move.selectedUnits.Add(Unit); //list of gameobjects
}
}
}
}