The question is answered, right answer was accepted
Can't apply AddForce after Instantiating object
I've been trying out different methods for a shooting script to try and make it as versatile as possible.
I've decided on something like this:
public GameObject bullet;
public float bulletSpeed = 1000f;
private Rigidbody bulletRB;
void Update ()
{
if (Input.GetMouseButtonDown (0))
{
GameObject.Instantiate (bullet, this.transform.position, this.transform.rotation);
bulletRB = bullet.GetComponent <Rigidbody> ();
bulletRB.AddForce (this.transform.forward * bulletSpeed);
}
}
But when the object is created it just falls without any force. I know it has something to do with how I'm applying the force, but I can't figure it out. Any help would be awesome!
Answer by Ahndrakhul · Mar 25, 2017 at 02:14 AM
It looks like you're trying to add force to the prefab of your bullet object and not the instantiated object.
Try something like this:
public GameObject bullet;
public float bulletSpeed = 1000f;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GameObject bulletInstance = Instantiate(bullet, transform.position, transform.rotation);
bulletInstance.GetComponent<Rigidbody>().AddForce(transform.forward * bulletSpeed);
}
}
Follow this Question
Related Questions
How can i make an object move to my aiming position? 0 Answers
Addforce is not working 1 Answer
Is there any good sample code for shooting a projectile and collision detection? 0 Answers
How to create smooth jump with rigidbody.addforce? 2 Answers
Rigidbody AddForce(transform.forward) vs Rigidbody.AddRelativeForce(transform.forward) ? 1 Answer