0
votes

I'm making a game where the player touches the screen and an object instantiates . However, I only want the object to instantiate if the Raycast hits an object that is on a specific layer (or of a specific tag if that is easier). I can get the ray to cast out and instantiate a prefab where I'd like it, but when I add in the section of checking for the layer, it sends me an error (NullReferenceException:Object reference not set to an instance of an object). This seems like such a simple thing but I can't get it to work. Any help would be GREATLY appreciated!

var box : Transform;



function Update ()
{

if (Input.GetMouseButtonDown(0))
{
if(roomController.noMore == false){
var hit : RaycastHit;
var mousePos : Vector3 = Input.mousePosition;
mousePos.z = 9;
var worldPos : Vector3 = camera.ScreenToWorldPoint(mousePos);
Debug.Log("Mouse pos: " + mousePos + " World Pos: " + worldPos + " Near Clip Plane: " + camera.nearClipPlane);

if(hit.collider.gameObject.layer == "Ground" && HierarchyType.collider != null){
clone = Instantiate(box, worldPos, Quaternion.identity);
noMore = true;
Destroy(this);
}

}
}
}
2

2 Answers

0
votes

Try use Physics.Raycast.

var hit : RaycastHit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hit))
{
    if (hit.collider != null && hit.collider.gameObject.layer == LayerMask.NameToLayer("Water"))
    {
        Debug.Log("Instantiate");
    }
}
0
votes

but when I add in the section of checking for the layer, it sends me an error (NullReferenceException:Object reference not set to an instance of an object).

This is probably because actually you are not casting any ray and checking that an hit actually occurred( avoid the relative collider field could be null).

I suggest you to have a look at Physics.RayCast overloads, it could be significant more efficient to specify the layer (through LayerMask) while casting instead of filtering the results later.