问题
I use SendMessage to inform the Object that is was hit by a Raycast:
using UnityEngine;
public class Raycaster : MonoBehaviour {
void Update() {
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit))
if(hit.transform.tag == "MyGameObject"){
hit.transform.SendMessage ("HitByRay");
}
}
}
And object have a script like this:
using UnityEngine;
public class ObjectHit : MonoBehaviour {
void HitByRay () {
Debug.Log ("I was hit by a Ray");
}
}
And that print message "I was hit by Ray" in every frame. Now i need to inform that Game Object that raycast not hitting it anymore.
回答1:
@Eddge is right, storing a reference to the hit gameobject is the way to go. Check the following code :
public class Raycaster : MonoBehaviour
{
private bool hitting = false;
private GameObject hitObject;
void Update()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit))
{
if(hit.transform.tag == "MyGameObject")
{
GameObject go = hit.transform.gameobject ;
// If no registred hitobject => Entering
if( hitObject == null )
{
go.SendMessage ("OnHitEnter");
}
// If hit object is the same as the registered one => Stay
else if( hitObject.GetInstanceID() == go.GetInstanceID() )
{
hitObject.SendMessage( "OnHitStay" );
}
// If new object hit => Exit last + Enter new
else
{
hitObject.SendMessage( "OnHitExit" );
go.SendMessage ("OnHitEnter");
}
hitting = true ;
hitObject = go ;
}
}
// No object hit => Exit last one
else if( hitting )
{
hitObject.SendMessage( "OnHitExit" );
hitting = false ;
hitObject = null ;
}
}
}
来源:https://stackoverflow.com/questions/45983775/making-an-object-detect-that-raycast-not-hitting-it-anymore