x


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?

more ▼

asked Jul 30 '10 at 02:33 AM

Jeff 3 gravatar image

Jeff 3
45 6 6 10

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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;
more ▼

answered Jul 30 '10 at 08:50 AM

jashan gravatar image

jashan
10.3k 25 43 117

The Transform... version worked. I am a http://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!

Jul 30 '10 at 01:28 PM Jeff 3

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() would return "MyScript" 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

Jul 30 '10 at 05:26 PM jashan
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1726
x38

asked: Jul 30 '10 at 02:33 AM

Seen: 2949 times

Last Updated: Jul 30 '10 at 06:56 AM