I want to determine if the unity object has been touched, but inspector settings
Is it bad?

Reference URL

Error message
NullReferenceException: Object reference not set to an instance of an object
GetClickedGameObject.getClickObject () (at Assets/Scripts/GetClickedGameObject.cs: 34)
GetClickedGameObject.Update () (at Assets/Scripts/GetClickedGameObject.cs: 20)
Applicable source code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class GetClickedGameObject: MonoBehaviour {
    GameObject clickedGameObject;
    // Use this for initialization
    void Start () {
    // Update is called once per frame
    void Update ()
        GameObject obj = getClickObject ();
        if (obj! = null)
            // Processing when the following object is clicked
        // Function to get left clicked object (2D)
        private GameObject getClickObject ()
            GameObject result = null;
            // Get the object at the left click location
            if (Input.GetMouseButtonDown (0))
                Vector2 tapPoint = Camera.main.ScreenToWorldPoint (Input.mousePosition);
                Collider2D collition2d = Physics2D.OverlapPoint (tapPoint);
                if (collition2d)
                    result = collition2d.transform.gameObject;
            return result;
  • Answer # 1

    First of all, official information.
    Null Reference Exception-Unity Manual

    And the error message has the exact cause.
    Assets/Scripts/GetClickedGameObject.cs: 34
    It seems to be line 34 of the GetClickedGameObject.cs file.

    Vector2 tapPoint = Camera.main.ScreenToWorldPoint (Input.mousePosition);
    This line is here, where is the object disappearing? SoCamera.mainis suspicious.
    This points to"Camera component of GameObject with tag" MainCamera "", so I think this probably doesn't exist.
    (When this code is executed, that is, it should not exist when left-clicked)
    please make sure.

Related articles