Rhys Edwards
Rhys Edwards

Reputation: 791

Destroying a prefab from mouse click raycast

I want to destroy or remove a spawning prefab from my scene when the mouse clicks on the gameobject. I'm trying to use the code below from the Unity docs, however I'm presented with the following error: object reference not set to the instance of an object.

This script is attached to my main camera. onclick crashes the game. Can anyone see where this is going wrong?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class onClickDestroy : MonoBehaviour
{
    public GameObject destroyCube;

    // Update is called once per frame
    void Update()
    {

        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit = new RaycastHit(); //*
            if (Physics.Raycast(ray, out hit)) //**
            {
                print("true" + hit.point);
            }
        }

    }
}

Upvotes: 0

Views: 44

Answers (1)

derHugo
derHugo

Reputation: 90580

Solution 1

Make sure your Camera is really tagged as MainCamera

enter image description here

if not click there and select MainCamera from the list

enter image description here

Solution 2

Get and check the main camera at game start

priavte Camera _camera;

privtae void Awake()
{
    _camera = Camera.main;

    if(!_camera)
    {
        Debug.LogError("No Camera tagged MainCamera in Scene!");
        enabled = false;
    }
}

Solution 3

Or instead of using Camera.main at all instead get the Camera component directly

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class onClickDestroy : MonoBehaviour
{
    public GameObject destroyCube;

    privtae Camera _camera;

    private void Awake()
    {
        _camera = GetComponent<Camera>();
    }

    // Update is called once per frame
    private void Update()
    {

        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit = new RaycastHit();
            if (Physics.Raycast(ray, out hit))
            {
                print("true" + hit.point);
            }
        }
    }
}

Upvotes: 1

Related Questions