Why does this not work?

I’m making a FPS on Unity (yeah yeah not original but who cares) and I’m doing okay. I’ve got the FPS control going with the camera following it, I got the imported models and particle effects. There’s just a problem that is preventing me from moving on to shooting targets and stuff. I made a little Instantiate script to make bullets appear. The appearing bit works but I want to add force to the bullets, of course, so I made this little Javascript:

var thePrefab : GameObject;
var power : float = 100.0;


function Update () {

if(Input.GetKeyDown(KeyCode.S)){
var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation);
thePrefab.rigidbody.AddForce(Vector3(0, 0, power));

Surely this should make the bullets shoot forwards by 100 units when I press the S button, right? Well, nothing happens. When I press S, the bullet appears and then drops to the ground because of rigidbody, but there’s no force! Any help!? Sorry if this is a really easy mistake, I’m still learning.

you don’t want to add a force to the prefab, you want to add the force to the instance you just created…

Okay…how do I do that?

    var thePrefab : GameObject;
    var power : float = 100.0;
     
     
    function Update () {
     
    if(Input.GetKeyDown(KeyCode.S)){
    var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation);
    instance.rigidbody.AddForce(Vector3(0, 0, power));

Didn’t work.

I’m gonna try and add a separate code for it.

I usually work in C#, try this:

        var thePrefab : GameObject;
        var power : float = 100.0;
         
         
        function Update () {
         
        if(Input.GetKeyDown(KeyCode.S)){
        var instance = Instantiate(thePrefab, transform.position, transform.rotation) as GameObjcet;
        instance.rigidbody.AddForce(Vector3(0, 0, power));

also if I remember correctly you should rather be looking at rigidbody.AddRelativeForce, but I might be wrong though.

instance.rigidbody.AddForce(new Vector3(0, 0, power)); // also try the 'new' before the Vector3

Okay, to all the poeple that are still reading, lol.

I made a separate script called Fire:

var force : float = 100;

function Update () {

if(Input.GetKeyDown(KeyCode.S)){
 rigidbody.AddForce(transform.forward * force);
 }

}

I added it to the prefab, pressed play, pressed S. Here’s what hapened; It dropped to the ground the first time I pressed S, then the second time, the one already on the ground was given force. How do I make it so that it’s instantly given force?

BOOM! FIXED IT! I just put the previous script I added into a Start function! It works now!

var force : float = 100;

 

function Start () {

 

if(Input.GetKeyDown(KeyCode.S)){

 rigidbody.AddForce(transform.forward * force);

 }

 

}
var force : float = 100;

 

function Start () {

 

if(Input.GetKeyDown(KeyCode.S)){

 rigidbody.AddForce(transform.forward * force);

 }

 

}