What is typed variable?

Hi Guys,

  1. What is typed variable?

  2. And Examples of it?

  3. which part of my code can be replaced with typed variables?

  4. and how does it speed up my game scene process?

  5. please do let me know if there’s anything else I need to know in order to understand typed variables better, thanks!

I got this question from my previous question, one of person suggested to me to use typed variables, but I don’t know what is it.

Below is coding( in javascript / unityscript) :

        private var ttag = "enemyAim";
        private var target : Transform;

        var closestEnemy : Transform = null;
        var dist : float;

        function getClosestEnemy () : Transform
         var taggedEnemys = GameObject.FindGameObjectsWithTag(ttag);
         var closestDistSqr = Mathf.Infinity;
         var closestEnemy : Transform = null;
         print("get closestEnemy");

         for (taggedEnemy in taggedEnemys) // this part (1)
          var objectPos = taggedEnemy.transform.position;
     dist = (objectPos - transform.position).sqrMagnitude;

 if (dist < 3.0)
 if (dist < closestDistSqr)
    closestDistSqr = dist;
    closestEnemy = taggedEnemy.transform;
         target = closestEnemy;

Thanks in advance!

  1. A typed variable is a variable that defines its type (Transform, Vector3, etc) explicitly. It is defined by adding “:VariableType” after the name of the variable.

  2. For example, this is a variable:

    var myPosition;

While this is a typed variable:

var myPosition:Vector3;
  1. Everything that says “var” con be assigned a type, as shown above

  2. If the engine knows the type of a variable, it won’t need to lose time to “guess” it, which leads to a faster performance. Also, you’ll notice that more errors are reported to you while you code instead than while you run the game, which is very good.

All variables are automatically typed for you, as long as you supply a value. You can optionally add types to your code where it doesn’t have them. For example:

private var ttag = "enemyAim";

can be written as

private var ttag : String = "enemyAim";

However this has no actual performance benefit, since both lines of code compile to the exact same thing. The compiler sees that you are assigning a string to the ttag variable, therefore it is typed as String. Writing out the type may help you understand the code better in some cases, but it’s optional. The only thing you should avoid doing is neglecting to supply both a type and a value, such as this:

var foo; // bad!

This can still work in some cases (desktop platforms where you’re not using #pragma strict), however it will be quite slow since the type has to be figured out at runtime. As long as you supply a type or a value (or both), then you’re fine.

(The person you’re referring to in the comments to your other question is mistaken, by the way. All of your variables are typed.)