- Home /
Why am I getting an error? Transform issue?
So I'm getting the error : InvalidCastException: Cannot cast from source type to destination type.
I suspect it might have something to do with gameObjects vs Transforms.
I'm still a little bit fuzzy on the difference between the two and was hoping someone could help me out and see what the error is here? It occurs when distancetonext is first referenced.
#pragma strict
var respawnPoints : Transform;
var points : List.<Transform>;
var numberofnextrespawnpoint : int = 1;
function Start () {
points = new List.<Transform>(respawnPoints.GetComponentsInChildren.<Transform>()) ;
pointOfRespawn = 'RespawnPoint1';
**(ERROR RIGHT HERE)** distancetonext = Vector3.Distance (transform.position, GameObject.Find(pointOfRespawn).transform.position);
nextPointofRespawn = 'RespawnPoint1';
}
function Update () {
if (pointOfRespawn == 'RespawnPoint1'){
numberofnextrespawnpoint = 0;
}
else{
numberofnextrespawnpoint = points.IndexOf(GameObject.Find(pointOfRespawn).transform) + 1;
}
if (numberofnextrespawnpoint > points.Count){
numberofnextrespawnpoint = 0;
}
print(points[numberofnextrespawnpoint]);
nextPointofRespawn = points[numberofnextrespawnpoint].gameObject;
distancetonext = Vector3.Distance (transform.position, GameObject.Find(nextPointofRespawn).transform.position);
respawnPointNumber = numberofnextrespawnpoint;
}
Answer by PippyLongbeard · Dec 31, 2013 at 12:16 AM
This hasn't been tested, but have you could try changing the second parameter for Vector3.Distance() from 'GameObject.Find(pointOfRespawn).transform.position' to 'GameObject.Find(pointOfRespawn).gameObject.transform.position'. This might solve your problem.
Answer by YoungDeveloper · Dec 31, 2013 at 12:21 AM
I am not sure, but i think you need to pre store the gameobject.
GameObject newGO = GameObject.Find(nextPointofRespawn);
distancetonext = Vector3.Distance (transform.position, newGO.transform.position);