使用Raycast2D检测对象

Hal*_*gun 3 unity-game-engine raycasting

我正在研究简单的策略游戏机制.我有一个军营预制件.当我在场景中添加军营并点击军营时,我收到一个NullReferenceException错误:

NullReferenceException:对象引用未设置为对象的实例PlacementController.Update()(在Assets/Scripts/PlacementController.cs:64)

当我尝试使用Raycast2D到达军营的对撞机名称时收到错误.

军营预制件有一个Box Collider2D对撞机(触发器被检查),其标签为"建筑物",其图层为"建筑物".它有一个刚体2D组件,它是一个运动刚体.

我无法弄清楚这个问题.请帮我.

谢谢你的时间.

using UnityEngine;
using System.Collections;

public class PlacementController : MonoBehaviour
{
    private Buildings buildings;
    private Transform currentBuilding;
    private bool _hasPlaced;
    public LayerMask BuildingsMask;
    public void SelectBuilding(GameObject g)
    {
        _hasPlaced = false;
        currentBuilding = ((GameObject)Instantiate(g)).transform;
        buildings = currentBuilding.GetComponent<Buildings>();
    }

bool CheckPosition()
{
    if (buildings.CollidersList.Count > 0)
    {
        return false;
    }
    return true;
}

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


    Vector3 m = Input.mousePosition;
    m = new Vector3(m.x, m.y, transform.position.z);
    Vector3 p = GetComponent<Camera>().ScreenToWorldPoint(m);


    if (currentBuilding != null && !_hasPlaced)
    {

        currentBuilding.position = new Vector3(p.x,p.y,0);

        if (Input.GetMouseButtonDown(0))
        {
            if (CheckPosition())
            {
                _hasPlaced = true;
            }
        }
    }
    else
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit2D hit = new RaycastHit2D();
            Ray2D ray2D = new Ray2D(new Vector2(p.x,p.y), Vector3.down );
            //Ray2D ray = new Ray(transform.position,new Vector3(p.x,p.y,p.z));
            if (Physics2D.Raycast(new Vector2(p.x,p.y),Vector3.down,5.0f,BuildingsMask) )
            {
                Debug.Log(hit.collider.name); //error
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

------------------我正在分享答案,谢谢你的帮助--------------------

 if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject())
        {
            RaycastHit2D hit = new RaycastHit2D();
            Ray2D ray2D = new Ray2D(new Vector2(p.x,p.y), Vector3.down );
            hit = Physics2D.Raycast(new Vector2(p.x, p.y), Vector3.forward, 5.0f, BuildingsMask);

                Debug.Log(hit.collider.name);

        }
Run Code Online (Sandbox Code Playgroud)

rut*_*ter 6

Unity有两个物理引擎,它们非常相似,但这是一个区域,它们以微妙和混乱的方式不同.

3D引擎提供Physics.Raycast,返回true命中或false其他方式,并允许您RaycastHit通过引用传递,如果您需要了解更多关于命中.

2D引擎提供Physics2D.Raycast,而不是返回RaycastHit2D命中或null其他.编写代码的方式,hit您访问的次数与光线投射调用返回的命中次数不同.

所以,你需要更接近这个:

RaycastHit2D hit = Physics2D.Raycast(...); //edit in your raycast settings
if (hit) {
    //do something with the hit data
}
Run Code Online (Sandbox Code Playgroud)

(您可能会注意到RaycastHit2D有隐式转换为bool.)

Unity很长一段时间只有3D引擎,所以很多旧的文档都会说话,就好像这是唯一一个.注意这一点.