Unity3D性能优化小tips——把this.transform缓存缓存起来

Unity3D开发时中有一个小tips,这在官方的文档里其实有提及的,但不那么显眼,这里小说一下;

在MonoBehaviour进行编程时,我们经常会用this.transform, this.gameObject等属性来获取指定的对象。

在Visual Studio中按F12进入定义可以看到,这些属性都是getter。我们的每一次调用,Unity内部会从GameObject里搜寻这些Component,会有一定的损耗,因此,像在Update里频繁需要用到transform这类组件的时候,可以把它们缓存起来。

function Update () {
    transform.Translate(0, 0, 5);
}

可以改成这样

private var myTransform : Transform;
function Awake () {
    myTransform = transform;
}

function Update () {
    myTransform.Translate(0, 0, 5);
}

自己常用的KKBehaivour类

而我的做法,是封装一个自己的XXXBehaviour类,去继承MonoBehaivour,把常用的一些组件存起来。实际使用上,更多的使用自己的XXBehaivour。
同时把Start, Awake, Update这些函数设置成虚函数,方便开发使用。

using UnityEngine;
using System.Collections;

public class KKBehaviour : MonoBehaviour
{
    public Transform _Transform;

    protected bool IsDeleted = false;

    static bool IsApplicationQuited = false;  // 全局标记, 程序是否退出状态

    public virtual void Awake()
    {
        _Transform = transform;
    }

    public virtual void Start()
    {

    }

    // Update is called once per frame
    public virtual void Update()
    {
    }

    public virtual void Delete()
    {
        GameObject.Destroy(gameObject);
    }

    // 只删除自己这个Component
    public virtual void DeleteSelf()
    {
        GameObject.Destroy(this);
    }

    // 程序退出时会强行Destroy所有,这里做了个标记
    protected virtual void OnDestroy()
    {
        IsDeleted = true;
    }

    void OnApplicationQuit()
    {
        IsApplicationQuited = true;
    }
}

==>官方脚本性能优化说明点这里

posted @ 2014-08-10 19:56  霖哥Kelly  阅读(1184)  评论(1编辑  收藏  举报