继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Component.transform属性使用时的优化

RayYang
关注TA
已关注
手记 2
粉丝 64
获赞 8

在 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 的属性,还是先缓存下来比较好.

打开App,阅读手记
5人推荐
发表评论
随时随地看视频慕课网APP