- Home /
InvalidCastException: Cannot cast from source type to destination type.
Hello I have this script and I was just wondering what I am doing wrong. I have looked all over the answers section and I cannot figure out my problem. Any help would be greatly appreciated. Thanks in advance.
The error: InvalidCastException: Cannot cast from source type to destination type. Spawner.spawn_OBJ () (at Assets/Spawner.js:8) Spawner.Update () (at Assets/Spawner.js:20)
The Script: var OBJ : GameObject; var spawn_postion; var timer = 0.0;
function spawn_OBJ ()
{
spawn_postion = Vector2 (12,-2);
var temp_spawn_OBJ = Instantiate(OBJ,spawn_postion, Quaternion.identity)as GameObject;
}
function Start () {
}
function Update () {
timer += Time.deltaTime;
if (timer > 5)
{
spawn_OBJ();
timer = 0.0 ;
}
}
Are you sure that you have accepted OBJ in inspector? (i.e., OBJ is not null?)
Answer by fafase · Mar 15, 2015 at 05:20 PM
This is a basic UnityScript issue that makes you realize why C# is way better (POV).
var spawn_postion;
function spawn_OBJ ()
{
spawn_postion = Vector2 (12,-2);
}
Regardless the typo on position, first you declare the spawn_position and do not provide any type so the compiler makes it an Object so that anything will do.
Then you try to assign a Vector2 to it but the reference is of type Object.
Now the solution:
var spawn_postion : Vector2;
This way you tell the compiler that you have nothing to provide but you want it to be of type Vector2.
The reason for that mistake is things of this type:
var spawn_postion = Vector2(0,0);
No type is provided but right on the declaration there a value given so the compiler is able to define the type of the reference.
C# requires type any time (lets forget about dynamic for now). I see some already coming up with :
How about var floatVar = 5.0f;
well a value is given in the declaration so the compiler is able to define the type.
var floatVar;
would never go in C#.