Making an object detect that raycast not hitting it anymore

回眸只為那壹抹淺笑 提交于 2019-12-25 08:57:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!