Error when using variable of one class with instan

2019-09-21 02:31发布

问题:

UPDATE

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**
}

回答1:

Look very close at this

public class WaypointsClass
{
    public GameObject[] waypoints;
}

WaypointsClass.waypoints is an ARRAY! You must use the new keyword to create array or stuff like that will happen. wp.waypoints = new GameObject[waypoints.Length];

It should look like this

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;

EDIT:

From your comment, you can re-use WaypointsClass wp = new WaypointsClass(); by putting WaypointsClass wp outside the Start function then initialize it in the Start function like below:

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;
}


回答2:

You need to construct the GameObject in the class WaypointsClass otherwise you will get a null pointer exception...

and if you do this:

wp.waypoints = waypoints;

and the waypoints of the right side is a null reference the you will get a NPE too.



回答3:

To try and elaborate a little in case it's not immediately apparent, you've never created any GameObject; the array waypoints is still empty, so when you try to call waypoints[0] (the value of currentWaypoint), the return is null; hence your (assumed) error: "NullReferenceException".

To resolve this, populate your array! Make a whole heap of GameObject and assign them positions.



回答4:

You haven't initialized the waypoints collection in MoveEnemy - you're attempting to assign null to wp.waypoints (I assume you're receiving a NullReferenceException...).