【问题标题】:Destroying a prefab from mouse click raycast从鼠标单击射线投射中销毁预制件
【发布时间】:2019-02-08 20:39:07
【问题描述】:

当鼠标点击游戏对象时,我想从我的场景中销毁或移除一个生成预制件。我正在尝试使用 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);
            }
        }

    }
}

【问题讨论】:

  • 你在哪一行得到异常?
  • Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

标签: visual-studio unity3d


【解决方案1】:

解决方案 1

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

如果没有点击那里并从列表中选择MainCamera

解决方案 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);
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-07-24
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多