2017-08-05 53 views
0

在我的項目中,我有一個MonoBehaviour類PlayerController,它包含另一個MonoBehaviour類WaypointController的對象數組。通過將對象拖放到檢查器中來填充此數組。問題是,在測試遊戲時,數組中的對象開始沒有問題,但變成了空值,我無法弄清楚爲什麼或者到底在哪裏。我沒有破壞對象(明知)或加載其他場景。我怎樣才能解決這個問題?MonoBehaviour對象變爲null

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

正在成爲空的對象是這個類的:

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

} 
+0

在發生此問題之前,您是否在運行時遇到任何錯誤? –

+0

不,我看不到。 – slec

回答

0

問題是播放器對象中,向其中的PlayerController是附件,從預製實例化。在一個對象中,其按鈕的onClick指向預製而不是實例。預製件在路點數組中沒有有效的對象。

我解決了這個問題,確保在設置按鈕的onClick時將GameObject播放器選作PlayerController.ContinueTour函數的源。