- Home /
Hit collider problem
Hi guys,
I've a problem with this code. I always end up with null reference and can't find a solution
using UnityEngine; using System.Collections;
public class MyTapHandler : MonoBehaviour {
public GameObject tapper;
// reference to our tap gesture recognizer object
public TapGestureRecognizer tapRecognizer;
void Start()
{
// register to the tap recognizer's OnTap event
tapRecognizer.OnTap += tapRecognizer_OnTap;
}
// our tap event handler method
void tapRecognizer_OnTap( TapGestureRecognizer source )
{
GameObject obj = PickObject( source.Position );
if( obj.GetInstanceID() == tapper.GetInstanceID()){ Debug.Log( "You tapped "); }else{ Debug.Log( "You didn't pressed the right object" );}
}
GameObject PickObject (Vector2 screenPos){
Ray ray = Camera.main.ScreenPointToRay( screenPos );
RaycastHit hit = new RaycastHit();
if ( Physics.Raycast( ray, out hit ) ) {
return hit.collider.gameObject;
} else{
return null;
}
} }
Check in what line does the error occur. $$anonymous$$ost probably then you have the answer. Check Window->Console and click on the error. it should tell you the line number after the :
Answer by corax · Mar 26, 2012 at 02:21 PM
Here is a clean code version
using UnityEngine;
using System.Collections;
public class MyTapHandler : MonoBehaviour {
public GameObject tapper;
// reference to our tap gesture recognizer object
public TapGestureRecognizer tapRecognizer;
void Start()
{
// register to the tap recognizer's OnTap event
tapRecognizer.OnTap += tapRecognizer_OnTap;
}
// our tap event handler method
void tapRecognizer_OnTap( TapGestureRecognizer source )
{
GameObject obj = PickObject( source.Position );
if( obj.GetInstanceID() == tapper.GetInstanceID())
Debug.Log( "You tapped ");
else
Debug.Log( "You didn't pressed the right object" );
}
GameObject PickObject (Vector2 screenPos){
Ray ray = Camera.main.ScreenPointToRay( screenPos );
RaycastHit hit = new RaycastHit();
if ( Physics.Raycast( ray, out hit ) )
return hit.collider.gameObject;
else
return null;
}
}
And here the console error:
MyTapHandler.tapRecognizer_OnTap (.TapGestureRecognizer source) (at Assets/Scripts/MyTapHandler.cs:24) TapGestureRecognizer.RaiseOnTap () (at Assets/Plugins/FingerGestures/Components/TapGestureRecognizer.cs:177) TapGestureRecognizer.OnActive (IFingerList touches) (at Assets/Plugins/FingerGestures/Components/TapGestureRecognizer.cs:133) GestureRecognizer.OnUpdate (IFingerList touches) (at Assets/Plugins/FingerGestures/Components/Base/GestureRecognizer.cs:181) FGComponent.FingerGestures_OnFingersUpdated () (at Assets/Plugins/FingerGestures/Components/Base/FGComponent.cs:34) FingerGestures.Update () (at Assets/Plugins/FingerGestures/FingerGestures.cs:973)NullReferenceException: Object reference not set to an instance of an object
post line 24. if I post your script in a text editor line 24 is empty. it shouldn't be in order to solve the problem .. :)