0

I'm having trouble when trying to make a dynamic variable like this example:

→ public TYPE_UNKNOW myType;

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

}

I appreciate all your replies.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

This is called an Implicit Type, when you want to do this you only have to declare a var type variable. The var keyword tells to the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

Example:

// 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

Sergio Ormeño
  • 389
  • 1
  • 8
  • Sergio is correct for local variables but you cannot use var for global variables. You could try "object" and see if that works. – Savlon Sep 23 '16 at 07:41