U3D-隐性的局部变量

var controller = GetComponent < CharacterController > ();

这个是js代码,但是一样可以用在C#代码。


当你在c#里面使用关键字var 作为局部变量,这就意味着编译器会尝试基于上文来解释变量的类型。这不同于动态变量,它能够够快的严格的定义变量的类型。


var controller = GetComponent < CharacterController > ();

CharacterController controller = GetComponent < CharacterController > ();


不管你使用以上的哪行代码,unity都会一样的编译。区别在于哪一个快慢。


建议:只使用在局部变量的情况,比如:

//This is okay, it is obvious here that the type is "Movement Controller"
var moveController = GetComponent<MovementController>();
 
//Less okay, not necessarily obvious what this function is returning
var properties = moveController.GetProperties();
 
//Unless it is obvious, this is probably a better approach
MoveProperties properties = moveController.GetProperties();
 
//This I am actually okay with, "targets" is defined right here in plain sight
GameObject[] targets = GameObject.FindGameObjectsWithTag( "Enemy" );
var firstTarget = targets[0];


示例:

using UnityEngine;
using System.Collections.Generic;
 
public class Player : MonoBehaviour
{
     //This is a member variable, so you can't use "var" here
     List<Transform> targets = new List<Transform>();
 
     void Update()
     {
         //You can only use them for local vars, like this!
         var firstTarget = targets[0];
 
         //Or even as iterator variables
         foreach (var target in targets)
         {
 
         }
     }
}


原文引用:http://unitypatterns.com/implicitly-typed-local-variables/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值