Problem converting JS in C#

Hello,
I try to convert this JS code:

var projectile : Transform;
var shot = Instantiate(projectile, transform.position, Quaternion.identity);
shot.rigidbody.AddForce(transform.forward * 3000);

into C# :

Transform projectile;
Object shot = Instantiate(projectile, transform.position, Quaternion.identity);
shot.rigidbody.AddForce(transform.forward * 3000);

but i get an error (CS1061) that “shot” doesn’t contain “rigidbody”.

Sorry for my bad English and thanks for any help.
Greetings Jannes

What is Object? I think you should use Rigidbody shot = …

C# is strongly typed, JS is weakly typed. You MUST declare the type of the shot if you wish to call a method or access a field of it. If it is declared as an Object, you can only call methods that Object has (obviously not rigidbody).

Maybe: GameObject shot = Instantiate(projectile, transform.position, Quaternion.identity) as GameObject;

That’s not the case actually. In the JS example, “var shot” is strongly typed as Transform since “projectile” is defined as Transform, and Instantiate returns the type of the object being instantiated in JS. JS uses implicit typing with “var” like C# does. So in C# you can do

var shot = Instantiate(projectile, transform.position, Quaternion.identity) as Transform;

Also it should be

public Transform projectile;

That won’t work since “projectile” is a Transform, so “shot” will be null. See my C# code above; “shot” should be defined as a Transform, either explicitly or implicitly.

–Eric

Thank you Eric :slight_smile: nice explanation. Problem solved!