- Home /
javascript to C# conversion; prefab objects
Having some trouble converting to C# here is the JS:
if(Input.GetKey(KeyCode.LeftShift)){
if(bulletCounter > fireRate){
var bulletPrefab = Instantiate(currentBullet, transform.position + Vector3(bulletPos,-0.25,0.01), Quaternion.Euler(0,180,0));
if(direction == true){
bulletPrefab.transform.rigidbody.velocity.x = bulletSpeed;
...
}
The problem is instantiating the prefab object. I've set it as a GameObject variable, public GameObject bulletPrefab;
but this isn't working...
Answer by perchik · Mar 03, 2014 at 04:57 PM
Look at the unity documentation for Instantiate and check the c# dropdown box
In C#, you have to cast it to a type, so you'll probably end up doing something like this:
Gameobject bulletPrefab = Instantiate(
currentBullet, transform.position +Vector3(bulletPos,-0.25,0.01),
Quaternion.Euler(0,180,0)) as GameObject;
Thanks, but that doesn't work. I get numerous errors when I try that. (and yes, even when correcting the "Gameobject" to "GameObject".
Assets/Scripts/newplayerweapons.cs(51,104): error CS0119: Expression denotes a type', where a
variable', value' or
method group' was expected
Assets/Scripts/newplayerweapons.cs(51,56): error CS1502: The best overloaded method match for UnityEngine.Object.Instantiate(UnityEngine.Object, UnityEngine.Vector3, UnityEngine.Quaternion)' has some invalid arguments Assets/Scripts/newplayerweapons.cs(51,56): error CS1503: Argument
#2' cannot convert object' expression to type
UnityEngine.Vector3'
$$anonymous$$y bad, I just fixed the Instantiate, but didn't fix everything else.
Try this
GameObject bulletPrefab = Instantiate(
currentBullet, transform.position + new Vector3(bulletPos.x, -0.25f, 0.01f),
Quaternion.Euler(0, 180, 0)) as GameObject;
A few comments: first, I don't know what bulletPos is, so I assumed its a Vector3 position. (but you can't pass a Vector3 to the xPos of a vector3, so I did .x
second, in c# floats have to have the letter f after them to indicate it's a float and not a double.
third, in c# you have to create a new vector3, ins$$anonymous$$d of just using vector3
Your answer
![](https://koobas.hobune.stream/wayback/20220613135255im_/https://answers.unity.com/themes/thub/images/avi.jpg)