且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-21 10:24:50

看看非常接近这个

public class WaypointsClass
{
    public GameObject[] waypoints;
}

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

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

像这样

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

从您的评论中,您可以重复使用WaypointsClass wp = new WaypointsClass();通过将WaypointsClass wp放在开始 函数之外,然后初始化它在

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