一.脚本策略
1.使用最快的方式获取组件
GetComponent<T> > GetComponetn(typeof(T)) > GetComponent(string)
2.移除空的回调定义
void Start(){
}
void Update(){
}
3.缓存组件引用
private HealthComponent _healthComponent;
void Awake(){
//在awake进行先缓存起来
_healthComponent = GetComponent<HealthComponent>();
}
void TakeDamage(){
//而不是在这里缓存
if(_healthComponent.health < 0){
}
}
以这种方式缓存组件引用,就不必每次需要它们时重新获取
- 共享计算输出
多个对象共享某些计算结果,可节省性能开销
当然,只有这些计算都生成相同的结果,才有效
5.Update,Coroutines 和InvokeRepeating
6.更快的GameObject空引用检查
if(gameObject ! = null ){
//对gameObject做一些事情
}
if(!System.Object.ReferenceEquals(gameObject,null)){
//对gameObject做一些事情
}
他运行速度大概是原来的2倍,虽然他混淆了代码的用途
7.避免从GameObject取出字符串属性
从GameObject中检索字符串属性是另一种意外跨域本机-托管桥接
for(int o=0;i<listOfObjects.Count;++i){
if(listOfObjects[i].tag = "Player'){
//使用gameObject.CompareTag(" Player"){可以避免本机-托管的桥接
//做一些事情
}
}
}