1. 程式人生 > 其它 >急!報錯:NullReferenceException: Object reference not set to an instance of an object

急!報錯:NullReferenceException: Object reference not set to an instance of an object

技術標籤:解決問題unityc#

急!報錯:NullReferenceException: Object reference not set to an instance of an object

使用Unity3D老是出現這種報錯,是真的煩,我覺得有必要記錄一下。

  • 原因

看了很多別人的說法,具體什麼原因我也不知道,我估計是沒有例項化。有需要的可以參考我的程式碼
我要實現的效果很簡單,就是在兩個物體之間連線,Linerenderer元件掛在空物體(“Line”)上,在我的報錯程式碼裡,只是定義了tether這一變數,但是並不知道tether指什麼,所以要使用find找到代指的東西。

  • 報錯程式碼
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DrawLine : MonoBehaviour {

    public Transform winch;
    public Transform uav;
    private LineRenderer tether;
    
    void Start () {
       
    }
	// Update is called once per frame
	void Update () {
        tether.
SetPosition(0, winch.position); tether.SetPosition(1, uav.position); } }
  • 解決程式碼(在start裡面加了一行程式碼):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DrawLine : MonoBehaviour {

    public Transform winch;
    public Transform uav;
    private LineRenderer
tether; void Start () { tether = GameObject.Find("Line").GetComponent<LineRenderer>(); } // Update is called once per frame void Update () { tether.SetPosition(0, winch.position); tether.SetPosition(1, uav.position); } }