Button Raycasting

Hi everybody :slight_smile:

Currently I am using this bit of code to check if the player is touching the phone over an object in 3D space:

var hitMask : LayerMask;

//Check Touches
function Update () {
	for (var i = 0; i < Input.touchCount; ++i) {
		if (Input.GetTouch(i).phase == TouchPhase.Ended) {
			// Construct a ray from the current touch coordinates
			var ray = Camera.main.ScreenPointToRay (Input.GetTouch(i).position);
			var hit : RaycastHit;
			if (Physics.Raycast (ray, hit, 100, hitMask)) {
				Debug.Log(hit.rigidbody.gameObject.layer);
				if (hit.rigidbody.GetComponent(PopupEvent_Click)) {
					//Trigger the popup click event if hit
					var popupEvent : PopupEvent_Click = hit.rigidbody.gameObject.GetComponent(PopupEvent_Click);
					popupEvent.PopupEvent();
				}
			}
		}
	}
}

Unfortunately, it’s having major issues with the layer mask. Specifically, if I don’t include the layer mask, then it does collide with the Ignore Raycast layer, and if I do include it, and tell it to only collide with layer 10 (named 3DGUI), then it doesn’t collide with anything.

Any help is greatly appreciated, thanks!

Do you set up the layer mask from the inspector or from code? You can include more than one layer in the layer mask and if you create your own mask then you need to add the Ignore Raycast layer (layer 2) explicitly.

Turns out the problem was in this line:

hit.rigidbody.GetComponent(PopupEvent_Click)

The collider that was getting hit was the child of the object with the rigidbody - which had a collider of its own.

So I had to move the parent collider to a new child object instead of being on the parent, and I had to do this code instead, so that I was referencing the object the impacting collider was attached to:

hit.collider.GetComponent(PopupEvent_Click)