【发布时间】:2018-05-04 11:47:39
【问题描述】:
我正在研究简单的策略游戏机制。我有一个兵营预制件。当我在场景中添加兵营并单击兵营时,收到NullReferenceException 错误:
NullReferenceException:对象引用未设置为对象 PlacementController.Update () 的实例(在 Assets/Scripts/PlacementController.cs:64)
当我尝试使用 Raycast2D 到达军营的对撞机名称时收到错误。
Barracks 预制件有一个 Box Collider2D 碰撞器(已选中触发器),其标签为“Building”,其层为“Buildings”。它有一个rigidbody2D 组件,它是一个运动学刚体。
我无法弄清楚这个问题。请帮帮我。
感谢您的宝贵时间。
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
}
}
}
}
-----------------我正在分享答案,感谢您的帮助------------------ -
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);
}
【问题讨论】:
标签: unity3d raycasting