- Home /
InvalidCastException in C#
I am trying to convert this Javascript to C#:
var bulletPrefab : Transform;
function Update().....
var bullet = Instantiate(bulletPrefab, GameObject.Find("gunPoint").transform.position, Quanternion.identity); bullet.rigidbody.AddForce(transform.forward);
C#
public Transform bulletPrefab;
void Update () { .....
GameObject bullet = (GameObject)Instantiate(bulletPrefab, GameObject.Find ("gunPoint").tranform.position, Quanterion.identity);
bullet.rigidbody.AddForce(transform.forward * 2000);
When I play the game, I am getting this error "InvalidCastException: Cannot cast from source type to destination type." What am I doing wrong?
Answer by jashan · Jul 30, 2010 at 08:50 AM
Have you tried replacing
GameObject bullet = (GameObject)Instantiate(bulletPrefab,
GameObject.Find("gunPoint").transform.position, Quanterion.identity);
with
Transform bullet = (Transform)Instantiate(bulletPrefab,
GameObject.Find("gunPoint").transform.position, Quanterion.identity);
?
If you need to get bullet as game object, you could do something like this:
Transform bulletTrans = (Transform)Instantiate(bulletPrefab,
GameObject.Find("gunPoint").transform.position, Quanterion.identity);
GameObject bullet = bulletTrans.gameObject;
The Transform... version worked. I am a VB.NET programmer so I am learning the C# syntax. I know this may not be Unity related, but it has do with this Instantiate syntax. Why do you need the syntax '(Transform)' in front of Instantiate?
Thank you for the help!
When it worked for you, you may consider "accepting" the answer (click the "check" symbol left of the up/down-vote arrows). Regarding "(Transform)": That's needed because Instantiate simply returns an Object, which you need to cast to the correct type "Transform". Since Unity 2.6 some methods are available in generic versions which makes this a bit less cumbersome, e.g. GetComponent<$$anonymous$$yScript>() would return "$$anonymous$$yScript" as such, so no type-casting needed. Some more info on typecasting: http://en.csharp-online.net/Typecasting or http://en.wikipedia.org/wiki/Type_conversion
Your answer
Follow this Question
Related Questions
InvalidCastException when using Instantiate 1 Answer
InvalidCastException C# 1 Answer
Invalid Cast Exception 1 Answer
Cannot cast from source type to destination type 1 Answer
Checking if object intersects? 1 Answer