我使用SendMessage来通知被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");
}
}
}
对象有一个这样的脚本:
using UnityEngine;
public class ObjectHit : MonoBehaviour {
void HitByRay () {
Debug.Log ("I was hit by a Ray");
}
}
那条打印信息"我被Ray"在每一帧。 现在我需要通知那个游戏对象光线投射不再打它了。
答案 0 :(得分:0)
@Eddge是对的,存储对命中游戏对象的引用是可行的方法。请检查以下代码:
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 ;
}
}
}