AddForce Problem ? [ Solved ]

Hi guys , i have a very easy problem about AddForce in Java Script. I did this a long time ago but i couldn’t remember how i did this. So , i want to make a shoot script . I wrote those ;

var mermiPrefab : GameObject;

function Update () 

{
    if (Input.GetButtonDown("Fire1") )
	{
	 Instantiate(mermiPrefab,transform.position,Quaternion.identity);
	 mermiPrefab.rigidbody.AddForce(transform.forward * 2000);
	}

}

When i click mouse 1 , mermiPrefab ( it’s bullet prefab ) appears but it’s not going forward , i put rigidbody in it , again it appears but this time it falls down. I mean AddForce didn’t work , is there any mistake about it ?

Rigidbody.AddForce has to be applied every frame to work. You can set the velocity of the rigidbody to some initial value and the physics engine will handle the evolution of the movement.

You need to save the result of Instantiate to a variable, then use that variable (and not the prefab).

For example:

[...]
    var newBullet = Instantiate(mermiPrefab,transform.position,Quaternion.identity); 
    newBullet.rigidbody.AddForce(transform.forward * 2000); 
[...]

Thanks a lot guys :slight_smile: , i solved the problem,thank you again :).

Hi Guys

Iam facing the same issues only im using “C sharp” as my programming language following is the code im using:

public class Fire_Bullet : MonoBehaviour {

public Rigidbody bullet;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
shootbullet();
}
void shootbullet(){
Rigidbody Clone;
if(Input.GetMouseButtonDown(0)){
Clone = (Rigidbody) Instantiate (bullet, this.transform.position, this.transform.rotation);
Clone.rigidbody.AddForce(0,0,1000);
}
}
}

OK so the problem is the the bullet gets Instantiate how ever it does not go in the direction i want it to go in please help.

Also after the object is Instantiate when I set it to get destroyed after say 2sec it does not get destroyed, I am using the following code to destroy the Instantiate object

“Destroy(Clone, 2);”

NOTE: I am new to Unity programming.

You are instantiating the bullet with the same orientation as the transform.

So, make sure the object in which that script is on, is pointing in the direction you want the bullet to go.

Or change the “this.transform.rotation” in the Instantiate for a rotation aiming at where you want.

OK but if its not possible to rotate the object then what should be done I mean how should I define the rotation that the instantiated object should take ?

Something like this:

Hey thanks for helping ,I will try it out n let u know :smile: