Unity Awake 和 Start 关于值初始化、惰性值和优化

众所周知,由于Unity中生命周期的设置,Awake将会在实例脚本载入时被调用一次,其后就不会再调用;而Start会在Update调用之前调用一次,故为了整体程序的负载降低,我们通常在Start中初始化我们的变量,以便该类或者其他类调用。

但是由于游戏模块设计中,基础类中的这些变量被大量依赖,上层类中可能会存在Awake中就调用底层类变量的情况,此时就可能会报Null错误,为了避免出现此类错误,并且达到优化系统的目的,在此需要引入惰性值的设计。

什么是惰性值?

用不成熟和浅薄的语言来说,对于Unity,得到一种在Start之前未被初始化,但是可以读取其值的变量,这种变量就是惰性值LazyValue。通过在Awake中给惰性值赋值(这种赋值并不是初始化的赋值,而是通过方法return的方式把值传递给惰性值的容器中,相当于property的get),这样就可以在该类Start调用前,让其他依赖于此类的类读取该惰性值中的内容。

        LazyValue<float> health;
        //在Awake中对其传递值
        private void Awake()
        {    
            health = new LazyValue<float>(GetInitialHealth);
        }
        //在Start中实例化
        private void Start()
        {
            health.ForceInit();
        }
        //传递值的方法
        private float GetInitialHealth()
        {
            return GetComponent<BaseStats>().GetStat(Stat.health);
        }

以下是取自https://www.udemy.com/course/unityrpg/learn/lecture/15211412#overview的LazyValue源文件,仅供学习参考。

namespace GameDevTV.Utils
{
    /// <summary>
    /// Container class that wraps a value and ensures initialisation is 
    /// called just before first use.
    /// </summary>
    public class LazyValue<T>
    {
        private T _value;
        private bool _initialized = false;
        private InitializerDelegate _initializer;

        public delegate T InitializerDelegate();

        /// <summary>
        /// Setup the container but don't initialise the value yet.
        /// </summary>
        /// <param name="initializer"> 
        /// The initialiser delegate to call when first used. 
        /// </param>
        public LazyValue(InitializerDelegate initializer)
        {
            _initializer = initializer;
        }

        /// <summary>
        /// Get or set the contents of this container.
        /// </summary>
        /// <remarks>
        /// Note that setting the value before initialisation will initialise 
        /// the class.
        /// </remarks>
        public T value
        {
            get
            {
                // Ensure we init before returning a value.
                ForceInit();
                return _value;
            }
            set
            {
                // Don't use default init anymore.
                _initialized = true;
                _value = value;
            }
        }

        /// <summary>
        /// Force the initialisation of the value via the delegate.
        /// </summary>
        public void ForceInit()
        {
            if (!_initialized)
            {
                _value = _initializer();
                _initialized = true;
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值