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/