zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
    

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

  • 相关阅读:
    #2019120500009-LG 数据结构 优先队列(1)
    #2019120500008-LG 数据结构 栈(1)
    2019D1T1 格雷码
    #2019120500006-LG 迷宫
    #2019120500004-LG 单词方阵
    #2019110700005
    hdu 1827强连通分量
    HDU 5691 状压dp
    HDU 4734--基础数位dp(递推)
    HDU 4638--莫队算法
  • 原文地址:https://www.cnblogs.com/mrkelly/p/3903272.html
Copyright © 2011-2022 走看看