好记性不如烂笔头。虽然是很细的东西,但是为了防止以后忘记,还是记一下比较好。 直接将代码挂到gameobject上,然后去检测Console面板。 代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class StayOrLeave : MonoBehaviour
{
//物体在屏幕内
void OnBecameVisible()
{
Debug.Log(gameObject.name +”出现(OnBecameVisible)”);
}

//物体在屏幕外
void OnBecameInvisible()
{
    Debug.Log(gameObject.name+"丢失(OnBecameInvisible)");
}

// 当可见时开启行为    
//function OnBecameVisible()
//{
//    enabled = true;
//}

}

官方解释: 当renderer(渲染器)在任何相机上可见时调用OnBecameVisible。 这个消息发送到所有附在渲染器的脚本上。 OnBecameVisible 和 OnBecameInvisible可以用于只需要在物体可见时才进行的计算。 OnBecameVisible可以被用作协同程序,在函数中调用yield语句。当在编辑器中运行时,场景面板相机也会导致这个函数被调用。 Unity圣典链接:http://www.ceeger.com/Script/MonoBehaviour/MonoBehaviour.OnBecameVisible.html