Cannot convert 'Object' to 'UnityEngine.Vector3'.

Hi all,

This give me an error saying “Cannot convert ‘Object’ to ‘UnityEngine.Vector3’” which is strange as obj.transform.position is a Vector3. Why is it saying that it is a datatype ‘Object’? Thanks in advance.

var startPos: Array;

    function Start() {
    
          startPos = new Array ();
    
          for ( var obj : GameObject in GameObject.FindGameObjectsWithTag("MyObj")) {
        
               startPos.Push (obj.transform.position);
        
          }
        
          transform.position = startPos[1];
    }

try:

var startPos: List.<Vector3> = new List.<Vector3>();

function Start() {

      for ( var obj : GameObject in GameObject.FindGameObjectsWithTag("MyObj")) {

           startPos.Add(obj.transform.position);

      }

      transform.position = startPos[1];
}

I also had quite a bit of trouble with Array() type, it seems like it only accepts primitives (like int,float,String) (might be incorrect though)

In any case Lists are often better and faster… but you can only put objects of one type in one list (for example Vector3 in this case)

What line is the error on?

It seems like it is probably with this line:

transform.position = startPos[1];

not the line in the for loop.


In which case, you’re saying: set transform.position (a Vector3 field) to be startPos[1] (an Object, even though you put a Vector3 in it, that information is not tracked by the compiler as JavaScript arrays do not support generics).

Consider using built-in arrays or a List type.

To obscure your particular error you should be able to use:

transform.position = startPos[1] as Vector3;

to hint to the compiler what type it will be, however I don’t think this is a particularly elegant solution as it overrides any static type checking.


This article gives more information on the various array/list container types you can use in Unity.