通过鼠标单击raycast销毁预制件

时间:2019-02-08 12:09:44

标签: visual-studio unity3d

当鼠标单击游戏对象时,我想从场景中销毁或删除生成的预制件。我正在尝试使用Unity文档中的以下代码,但是出现以下错误: object reference not set to the instance of an object

此脚本已附加到我的主相机上。 onclick使游戏崩溃。谁能看到这是怎么回事?

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

    }
}

1 个答案:

答案 0 :(得分:1)

解决方案1 ​​

确保您的Camera确实被标记为MainCamera

enter image description here

如果不单击此处,然后从列表中选择MainCamera

enter image description here

解决方案2

在游戏开始时获取并检查主摄像头

priavte Camera _camera;

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

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

解决方案3

或者完全不使用Camera.main而是直接获取Camera组件

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