- Home /
Cannot cast from source to destination type
I keep getting this error and I haven't a clue as to why; other than it has to do with this script. Please help me understand why this is happening
var Player : Transform; var rotateAmount = 90; var controller : CharacterController; var Hit : RaycastHit;
function Start(){ } function FixedUpdate (){
//casts a ray from camera to point in world var ray = Camera.main.ScreenPointToRay (Input.mousePosition); // If the controller is grounded and the ray hits an object; then you can Rotate walls if ((controller.isGrounded) && (Physics.Raycast (ray, Hit, 50))) { canRotate =true;
var Hitobject : GameObject = Hit.transform.gameObject && Hit.collider; var pivot : Transform = Hitobject.transform; if (Hitobject.tag == "Left"){ if(Input.GetMouseButtonDown(0)) RotateObjectForward(Player.position,pivot.forward, 90,1); if(Input.GetMouseButtonDown(1)) RotateObjectForward(Player.position,-pivot.forward,90,1); } }
Answer by by0log1c · Apr 27, 2011 at 05:36 AM
I'm not certain that is all there is to it but :
var Hitobject : GameObject = Hit.transform.gameObject && Hit.collider;
should probably be:
var Hitobject : GameObject = Hit.transform.gameObject;
A "Cannot cast from source to destination type" is well... an invalid-cast error. In other words, you're trying to reference an incorrect type into a type-restricted variable. For examples:
var number:int = "ThisIsNotAnInt";
var gameObject:GameObject = 9000;
var custom:MyCustomType = "NotMyCustomType";
would - I believe - all throw the exception. Note that JScript allow for dynamic casting, such as:
var unrestrictedType = "ICanJustReferenceWhateverTypeIWantHere";
var unrestrictedType = 1337;
var unrestrictedType = 3.1415926535;
would - I believe - never throw the exception, though errors might arise later.
Just to note, that's not dynamic casting, that's type inference. It's not limited to JS; C# also does that (the last few lines would compile as-is in C#). It infers the type from the value supplied when the variable is declared, but you can't change the type later, so it's not dynamic. Doing "`var blah = "foo";`" (JS/C#) is absolutely identical to doing "`var blah : String = "foo";`" (JS) or "`string blah = "foo";`" (C#).
Ah thank you! you were absolutely right about that part. Now I just need to figure out why my tag won't work.
Ahh, I didn't know C# allowed type inference. Then I can keep my overloading functions untyped when converting to C#... Awesome news :D!
@$$anonymous$$$$anonymous$$7 Give it a try and ask a separate question if needs be!
Your answer
Follow this Question
Related Questions
InvalidCastException: Cannot cast from source type to destination type. 4 Answers
"Cannot cast from source type to destination type"- instantiating 4 Answers
InvalidCastException: Cannot cast from source type to destination type. 1 Answer
unable to cast from source to destination 0 Answers
Cannot cast from source type to destination type ERROR! 2 Answers