使用一个类的变量与另一个类的实例时出错 [英] Error when using variable of one class with instance of another

查看:182
本文介绍了使用一个类的变量与另一个类的实例时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


推荐答案

看看非常接近这个

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

这篇关于使用一个类的变量与另一个类的实例时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆