亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Component.transform屬性使用時的優化

標簽:
Unity 3D

在 Unity 中, Component.transform 是我们经常会用到的.
比如:

void Start(){
    transform.position = Vector3.Zero;
}

但是要知道 transform不是一个变量,他是一个属性
图片描述
所以假如我们频繁的要使用 transform 的时候,那效率可就不好说了.最好的方法是我们把要频繁使用的 transform 用变量先缓存一下然后再使用,我们可以用一段代码来测试一下:

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

public class CacheTransformStopWatch : MonoBehaviour {

    public Transform trans;

    public int Count = 10000;

    private long NoCache = 0;
    private long Cache = 0;

    private void Start () {
        trans = this.transform;

        Stopwatch sw = new Stopwatch ();
        sw.Start ();
        for (int i = 0; i < Count; i++) {
            Transform t = this.transform;
        }
        sw.Stop ();
        NoCache = sw.ElapsedTicks;

        sw.Reset ();

        sw.Start ();
        for (int i = 0; i < Count; i++) {
            Transform t = trans;
        }
        sw.Stop ();
        Cache = sw.ElapsedTicks;
    }

    private void OnGUI () {
        GUILayout.Label (string.Format ("No Cache : {0}", NoCache));
        GUILayout.Label (string.Format ("Cache : {0}", Cache));
    }
}

我们随便把脚本挂在一个物体上运行一下
图片描述

我们可以看到,缓存之后比没缓存,速度快了将近4倍.所以在平时的开发中要是需要频繁的使用 transform 的属性,还是先缓存下来比较好.

點擊查看更多內容
5人點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消