Unity3d 性能优化遐想 OnBecameVisible/OnBecameInvisible

本文介绍如何在Unity中使用OnBecameVisible和OnBecameInvisible事件来实现物体进出视口的事件处理,通过实例演示了如何在物体进入或离开视口时触发特定操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当玩家在主城中行走时,周围大量玩家显示在玩家周围,不管是玩家能看到的前方,还是看不到的后方,所有的人物模型都在进行着脚本运算。

在OpenGL中 提供了裁剪功能,不在视口范围内的点和面会被裁剪掉以减少渲染代价,在Unity中也顺势提供了相关的API,提供物体进入/离开 视口的函数回调。

文章转自http://blog.csdn.net/huutu   http://www.thisisgame.com.cn

OnBecameVisible/OnBecameInvisible


当物体进入视口,触发 OnBecameVisible 。

离开视口时,触发 OnBecameInvisible 。

文章转自http://blog.csdn.net/huutu   http://www.thisisgame.com.cn

文章转自http://blog.csdn.net/huutu   http://www.thisisgame.com.cn

在摄像机前后添加 CubeRed 、 CubeBlue 。分别挂上脚本 CubeRed.cs 、CubeBlue.cs 。摄像机挂上旋转控制脚本 CameraControl.cs 。

文章转自http://blog.csdn.net/huutu   http://www.thisisgame.com.cn

using UnityEngine;
using System.Collections;

public class CameraControl : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
        transform.Rotate(0, 10*Time.deltaTime, 0);
	}
}


using UnityEngine;
using System.Collections;

public class CubeBlue : MonoBehaviour
{

    bool mVisible = false;

	// Use this for initialization
	void Start () {
        Debug.Log("CubeBlue Start");
	}
	
	// Update is called once per frame
	void Update () {
        if (mVisible)
        {
            //Debug.Log("CubeBlue Update");
        }
        
	}

    void OnBecameVisible()
    {
        Debug.Log("CubeBlue OnBecameVisible");
        mVisible = true;
    }

    void OnBecameInvisible()
    {
        Debug.Log("CubeBlue OnBecameInvisible");
        mVisible = false;
    }

}


using UnityEngine;
using System.Collections;

public class CubeRed : MonoBehaviour
{

    bool mVisible = false;

	// Use this for initialization
	void Start () {
        Debug.LogError("CubeRed Start");
	}
	
	// Update is called once per frame
	void Update () {
        if (mVisible)
        {
            //Debug.LogError("CubeRed Update");
        }
        
	}

    void OnBecameVisible()
    {
        Debug.LogError("CubeRed OnBecameVisible");
        mVisible = true;
    }

    void OnBecameInvisible()
    {
        Debug.LogError("CubeRed OnBecameInvisible");
        mVisible = false;
    }

}


运行后,摄像机开始旋转。当蓝色方块进入可视范围后,触发OnBecameVisible 回调。


工程下载
http://pan.baidu.com/s/1eQld5HC

文章转自http://blog.csdn.net/huutu   http://www.thisisgame.com.cn

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值