C# Unity3D移动问题(基于网格的寻路)
我目前正试图将我的角色移动到我的鼠标目标。两周以来我做了很多研究,我感觉离我的目标很近,但我仍然在努力。在按下play之前,我收到以下警告:C# Unity3D移动问题(基于网格的寻路),c#,unity3d,multidimensional-array,path-finding,C#,Unity3d,Multidimensional Array,Path Finding,我目前正试图将我的角色移动到我的鼠标目标。两周以来我做了很多研究,我感觉离我的目标很近,但我仍然在努力。在按下play之前,我收到以下警告: Assets\Scripts\Worldmaps\Movement.cs(11,12):警告CS0649:字段“Movement.path”从未分配给,并且其默认值始终为null 当我按play键时,在单击任何节点后,我会出现以下错误: NullReferenceException:对象引用未设置为对象的实例 Movement.Update()(位于Ass
Assets\Scripts\Worldmaps\Movement.cs(11,12):警告CS0649:字段“Movement.path”从未分配给,并且其默认值始终为null
当我按play键时,在单击任何节点后,我会出现以下错误:
NullReferenceException:对象引用未设置为对象的实例
Movement.Update()(位于Assets/Scripts/Worldmaps/Movement.cs:24)
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
private const float speed = 10f;
private int targetIndex;
Vector3[] path;
private Pathfinding pathfinding;
void Awake()
{
pathfinding = GetComponent<Pathfinding>();
}
private void Update()
{
if(Input.GetMouseButtonDown(0))
{
Vector3 target = GetMouseWorldPosition();
pathfinding.StartFindPath(transform.position, target);
targetIndex = 0;
Vector3 finalPath = path[0];
while(true)
{
if(transform.position == finalPath)
{
targetIndex++;
if(targetIndex >= path.Length)
{
break;
}
finalPath = path[targetIndex];
}
transform.position = Vector3.MoveTowards(transform.position, finalPath, speed * Time.deltaTime);
}
Debug.Log(target);
}
}
public static Vector3 GetMouseWorldPosition()
{
Vector3 clickPosition = new Vector3();
clickPosition.y = 0;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit))
{
clickPosition = hit.point;
}
return clickPosition;
}
}
提前谢谢你
Flowergun:)在使用Vector3[]路径数组之前,必须先实例化它。因此,在Awake()中,只需使用以下命令实例化它:
path = new Vector3[<write the length of the array here>];
如果不确定数组中对象的长度或数量经常更改,最好使用列表而不是数组 谢谢@KBaker它似乎清除了我的警告:)没问题!你能选择我的答案吗?非常感谢。
path = new Vector3[<write the length of the array here>];
path = new Vector3[5];