Having trouble using AddForce on prefab

Hi all,

I’m trying to launch a ball at the start of my game. I am able to instantiate the ball onto the field at the start of the game, but can’t seem to launch the ball using the method in the Update function or via Invoke in the start function.

Not sure what I am missing as the method worked on the ball when I applied the script directly to it.

public class BallSpawnManager : MonoBehaviour
{

    public float launchSpeed;
    public GameObject ballPrefab;
    private Vector3 startBallPosition = new Vector3(0f, 0.5f, 7.65f);

    public Rigidbody ballRb;
    // Start is called before the first frame update
    void Start()
    {
        Instantiate(ballPrefab, startBallPosition, Quaternion.identity);
        ballRb = ballPrefab.GetComponent<Rigidbody>();
       
    }

    // Update is called once per frame
    void Update()
    {
       
    }

    private void FixedUpdate()
    {
        LaunchBall();
    }

    private void LaunchBall()
    {
        ballRb.AddForce(ballRb.velocity.x, ballRb.velocity.y, launchSpeed * 2);
       
    }

I double checked my editor and the ballPrefab is correctly added and the Ball prefab has a rigidbody and all the correct settings, as this method worked when I directly attached it to the ball.

Line 13 gets the Rigidbody from the prefab.

That’s not going to be useful to you, since it is sitting on disk, not actually in your scene.

Line 12’s Instantiate call returns a GameObject reference to the ACTUAL ball in scene.

Get the Rigidbody from the returned reference and use that.

1 Like

Thank you Kurt, thank you very much!

1 Like