将一个类的变量与另一个类的实例一起使用时出错

时间:2016-03-20 16:10:29

标签: c# arrays class unity3d

更新

public class WaypointsClass
{
    public GameObject[] waypoints;
}


public class MoveEnemy : MonoBehaviour {

    public GameObject[] waypoints;
    private WaypointsClass wp;
    private int currentWaypoint = 0;

    void Start () {
       WaypointsClass wp = new WaypointsClass();
        wp.waypoints = new GameObject[waypoints.Length];
        wp.waypoints = waypoints;
print( wp.waypoints[currentWaypoint].transform.position); **WORKING**

}

void Update () {
print(wp.waypoints[currentWaypoint].transform.position);  **NOT WORKING**
}

4 个答案:

答案 0 :(得分:2)

非常接近这个

public class WaypointsClass
{
    public GameObject[] waypoints;
}

WaypointsClass.waypoints ARRAY !您必须使用new关键字创建数组或类似的内容。 wp.waypoints = new GameObject[waypoints.Length];

应该看起来像这样

public class MoveEnemy : MonoBehaviour {

    public GameObject[] waypoints;
    private WaypointsClass wp;
    private int currentWaypoint = 0;

    void Start () {
        WaypointsClass wp = new WaypointsClass();
        wp.waypoints = new GameObject[waypoints.Length]; //This line you missed
        wp.waypoints = waypoints;
        Vector3 startPosition = wp.waypoints[currentWaypoint].transform.position;

修改

从您的评论中,您可以重复使用WaypointsClass wp = new WaypointsClass(); 将WaypointsClass wp置于Start 函数之外,然后在Start 函数初始化,如下所示:

WaypointsClass wp = null; //Outside (Can be used from other functions)
void Start () {
            wp = new WaypointsClass(); //Init
            wp.waypoints = new GameObject[waypoints.Length]; //This line you missed
            wp.waypoints = waypoints;
            Vector3 startPosition = wp.waypoints[currentWaypoint].transform.position;
}

答案 1 :(得分:0)

您需要在 WaypointsClass 类中构建 GameObject ,否则您将获得空指针异常......

如果你这样做:

wp.waypoints = waypoints;

并且右侧的航点是空参考,您也将获得NPE。

答案 2 :(得分:0)

您尚未在MoveEnemy中初始化航点集合 - 您尝试将null分配给wp.waypoints(我假设您收到了NullReferenceException .. )。

答案 3 :(得分:0)

如果没有立即明白,试着再详细说明一下,你从未创造过任何GameObject;数组路径点仍为空,因此当您尝试调用waypoints [0](currentWaypoint的值)时,返回值为null;因此你的(假设的)错误:“NullReferenceException”。

要解决此问题,请填充阵列!制作一堆GameObject并为它们分配位置。