2016-09-22 105 views
0

试图使一个动态变量这样的例子,当我有麻烦:Unity3D动态变量声明

→ public TYPE_UNKNOW myType; 

void Awake(){ 
//i want to make myType as SpriteRenderer Or Image or int float etc. 

} 

我感谢所有的答复。

+0

使其对象作为皆是。但不知道这种类型通常不是一个好的起始案例。 – Everts

+0

也可以使用'dynamic'。我不知道这是否真的能够统一起作用,但现在无法对它进行测试。 –

+1

呃...只是想知道,为什么你想在运行时的未知类型的公共变量,反正呢?你有什么用途呢? – Serlite

回答

0

这叫做隐式类型,当你想这样做时,你只需要声明一个var类型变量。 var关键字告诉编译器从初始化语句右侧的表达式推断变量的类型。

实施例:

// i is compiled as an int 
var i = 5; 

// s is compiled as a string 
var s = "Hello"; 

// a is compiled as int[] 
var a = new[] { 0, 1, 2 }; 

// expr is compiled as IEnumerable<Customer> 
// or perhaps IQueryable<Customer> 
var expr = 
    from c in customers 
    where c.City == "London" 
    select c; 

// anon is compiled as an anonymous type 
var anon = new { Name = "Terry", Age = 34 }; 

// list is compiled as List<int>        
var list = new List<int>(); 

Source

+0

Sergio对于局部变量是正确的,但不能将var用于全局变量。你可以尝试“对象”,看看是否有效。 – Savlon