MonoBehaviour对象变为null

时间:2017-08-05 19:57:25

标签: c# unity3d

在我的项目中,我有一个MonoBehaviour类,PlayerController,它包含另一个MonoBehaviour类的对象数组WaypointController。通过将对象拖动到Inspector中来填充此数组。问题是数组中的对象在测试游戏时开始时很好,但是变为空,我无法弄清楚为什么或确切地在哪里。我不是在摧毁物体(故意)或加载其他场景。我该如何解决这个问题?

WaypointController对象封装了CanvasGroup,我在游戏中切换CanvasGroup的alpha和可交互字段。

这是包含数组的类:

public class PlayerController : MonoBehaviour {
    // This is the array that is populated from the Inspector
    // by dragging and dropping objects. 
    public WaypointController[] waypoints;
    int currentWaypoint = 0;

    // Called whenever a button in a WaypointController's canvas is clicked.
    public void ContinueTour() {
        Debug.Log ("Continuing tour");
        Debug.Log("ContinueTour: currentWaypoint=" + currentWaypoint);
        if (waypoints [currentWaypoint] != null) {
            Debug.Log ("Hiding waypoint " + currentWaypoint);
            waypoints [currentWaypoint].HideDescription ();

        } else {
            // This message is not displayed for the first WaypointController,
            // but it starts being displayed by the time second 
            // WaypointController is current.
            Debug.Log ("ERROR: Current waypoint is null");
        }
    }
}

变为null的对象属于此类:

public class WaypointController : MonoBehaviour {

    Canvas waypointDescriptionCanvas;
    CanvasGroup canvasGroup;


    void Awake() {
        waypointDescriptionCanvas = GetComponentInChildren<Canvas> ();

        if (waypointDescriptionCanvas == null) {
            Debug.Log ("Could not get canvas.");
        } else {
            Debug.Log ("Disabling description");
            // The description is not visible initially.
            canvasGroup = waypointDescriptionCanvas.GetComponent<CanvasGroup>();
            HideDescription();

        }
    }

    // Make the description canvas visible.
    public void ShowDescription() {
        Debug.Log ("ShowDescription");
        Vector3 direction = waypointDescriptionCanvas.transform.position - Camera.main.transform.position;
        waypointDescriptionCanvas.transform.forward = direction;
        canvasGroup.alpha = 1;
        canvasGroup.interactable = true;
    }

    public void HideDescription() {
        Debug.Log ("HideDescription");
        if (canvasGroup != null) {
            canvasGroup.alpha = 0;
            canvasGroup.interactable = false;

        } else {
            Debug.Log ("canvasGroup is null");
        }
    }

}

1 个答案:

答案 0 :(得分:0)

问题是PlayerController附加的Player对象是从预制件实例化的。在一个对象中,其按钮的onClick指向预制件而不是实例。预制件在路点阵列中没有有效的对象。

我通过确保在设置按钮的onClick时选择GameObject播放器作为PlayerController.ContinueTour函数的源来解决了这个问题。