關於「NullReferenceException: Object reference not set to an instance of an object」的思考

1、執行Vector2 screen_xy = Camera.main.WorldToScreenPoint(transform.position)時,報 「NullReferenceException: Object reference not set to an instance of an object」異常報錯。提示對象引用未設置爲對象的實例

 

1) 剛開始認爲是transfrom對應的object對象未實例化原因,因此嘗試直接輸入:Vector3 a = new Vector3(0.0f, 0.0f, 0.01f),這樣操作可以直接排除是受transform object的影響。但是,並未解決異常,報相同錯誤。

2)也懷疑是Vector2 screen_xy未進行實例化原因,嘗試:Vector2 screen_xy = new Vector2(0.0f, 0.01f)。但是,仍然未解決問題,報相同錯誤。

3)最後,鎖定爲Camera.main.WorldToScreenPoint()這個方法,存在未實例化對象問題。只能是Camera.main,通過該網址:https://csharp.hotexamples.com/examples/-/Camera/ScreenToWorldPoint/php-camera-screentoworldpoint-method-examples.html

如下圖提示:

    發現兩點:第一,Camera是一個類,通過類名調用函數,但是程序中未申請有Camera類。第二,Camera.main默認的是初始化攝像頭就是「Main Camera」,但是本Scene是初始化的「Camera」。

 

  1. 解決的方法是:

實例化一個Camera類對象mainCamera,並將其綁定到「Main Camera」上,在用mainCamera取代「Camera.main」,即可實現提取空間座標系下對應的屏幕座標。