欢迎光临散文网 会员登陆 & 注册

Unity脚本优化(一)

2020-05-09 17:55 作者:unity_某某师_高锦锦  | 我要投稿

Before优化前


void TakeDamage() {

    if (GetComponent<HealthComponent>().health < 0) {

    GetComponent<Rigidbody>().detectCollisions = false;

    GetComponent<Collider>().enabled = false;

    GetComponent<AIControllerComponent>().enabled = false;

    GetComponent<Animator>().SetTrigger("death");

    }

}


After优化后


// private variables to store cached references

private HealthComponent _healthComponent;

private Rigidbody _rigidbody;

private Collider _collider;

private AIControllerComponent _aiController;

private Animator _animator;


// cache the references during initialization

void Awake() {

_healthComponent = GetComponent<HealthComponent>();

_rigidbody = GetComponent<Rigidbody>();

_collider = GetComponent<Collider>();

_aiController = GetComponent<AIControllerComponent>();

_animator = GetComponent<Animator>();

}


// use the cached references at runtime

void TakeDamage() {

if (_healthComponent.health < 0) {

_rigidbody.detectCollisions = false;

_collider.enabled = false;

_aiController.enabled = false;

_animator.SetTrigger("death");

}

}


Unity脚本优化(一)的评论 (共 条)

分享到微博请遵守国家法律