0

I'm trying to add a force to the Rigidbody component of an instantiated projectile in Unity. I want to use this method as it is a simple throw mechanic and I just want the projectile to move in a small parabolic trajectory. The projectile prefab has already been attached to this script in the Unity editor and it does have a Rigidbody component.

Here's my code so far:

private void ProjectileShoot()
    {
        if (Input.GetKeyDown(KeyCode.LeftShift) && !gameOver)
        {
            Rigidbody projectileRb = projectilePrefab.GetComponent<Rigidbody>();
            Instantiate(projectilePrefab, transform.position, 
                projectilePrefab.transform.rotation);
            projectileRb.AddForce(throwForce * Vector3.forward, ForceMode.Impulse);
        }
    }

The projectile prefab spawns at the player's location as expected but it just falls to the ground straight away. No matter how much throwForce I apply to it.

ProjectileShoot() is in Update() by the way.

I am very much an amateur at C# and Unity and this is my first project so any help is appreciated. Thank you.

pjjanas
  • 23
  • 1
  • 5

2 Answers2

3
private void ProjectileShoot()
{
    if (Input.GetKeyDown(KeyCode.LeftShift) && !gameOver)
    {
        GameObject projectileGO = (GameObject) Instantiate(projectilePrefab, transform.position, 
            projectilePrefab.transform.rotation);

        Rigidbody projectileRb = projectileGO.GetComponent<Rigidbody>();
        projectileRb.AddForce(throwForce * Vector3.forward, ForceMode.Impulse);
    }
}

What you were doing before was trying to grab the Rigidbody from the prefab, however this is not possible. Instead, grab the Rigidbody from the instance by setting it to a variable when you instantiate it.

nullFoo
  • 71
  • 1
  • 7
1

Rigidbody projectileRb = projectilePrefab.GetComponent<Rigidbody>();

Referencing the rigidbody of the prefab.

Instantiate(projectilePrefab, transform.position, 
            projectilePrefab.transform.rotation);

A new entity is instantiated with the prefab.

projectileRb.AddForce(throwForce * Vector3.forward, ForceMode.Impulse);

The force is applied to the referenced rigidbody.


You are creating a new entity but not accessing its rigidbody, instead the rigidbody of the prefab is being used. To fix this, while instantiting the new entity i.e gameobject of the prefab, keep a reference of it and use it's rigidbody to apply the force.

GameObject projectile = (GameObject) Instantiate(projectilePrefab, transform.position, 
projectilePrefab.transform.rotation);

Rigidbody rb = projectile.GetComponent<Rigidbody>();
projectileRb.AddForce(throwForce * Vector3.forward, ForceMode.Impulse);