AddForce to instantiated GameObject

Hi, i want my character to throw shurikens from his hand in the direction of mouse.
Now it just spawns and fall down without any force.

public GameObject starPrefab;
    public Transform hand;
    public Transform player;
    public float speed;




    void Update()
    {



        Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 12);
        mousePos = Camera.main.ScreenToWorldPoint(mousePos);

        if (Input.GetMouseButtonDown(1))
        {
            Instantiate(starPrefab, hand.transform.position, player.rotation);
            starPrefab.GetComponent<Rigidbody>().AddForce((mousePos) * speed);
        }



    }

if I add ,starPrefab =" before Instantiate, It’s just spawning (clone), (clone)(clone),(clone)(clone)(clone) etc. and correctly adding force to the mouse. I wouldn’t have a problem with that if spawning stopped working when last (clone) is destroyed (simple timed self destroy script on the star prefab). So how do I add the force to this instantiated object?

Prefabs are the blueprint and Instantiate returns the instance created from the blueprint. Right now, you’re trying to add force to the prefab, which will have no effect. If you overwrite the starPrefab variable, you will then create copies of the instance in the scene, and when that instance is deleted, you won’t be able to create more.

Instead, assign the instance to a new variable:

var instance = Instantiate(starPrefab, hand.transform.position, player.rotation);
instance.GetComponent<Rigidbody>().AddForce((mousePos) * speed);
5 Likes

That works, kind of, finally spawning and throwing not just falling. No matter if character facing left or right, on right screen the force is as it should be, on left side the force is weaker.
Failed to upload video, so at least this: - Find & Share on GIPHY Not the best quality, but still can see what the problem is.

Edit: Problem solved as soon as I posted this reply. In the codevar instance = Instantiate(starPrefab, hand.transform.position, player.rotation);
I just added transform to the player.rotation

var instance = Instantiate(starPrefab, hand.transform.position, player.transform.rotation);

@Adrian i did this, but i got a compiler error saying that i don’t have rigidbody on my newly instantiated object, aka my bullet, and i don’t know how to get components onto the prefab. help?

Please don’t necro-post to ancient unrelated threads. Set yourself up for success: start a fresh post.

When you post, here is how to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, especially any errors you see
  • links to documentation you used to cross-check your work (CRITICAL!!!)

If you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: https://discussions.unity.com/t/481379

1 Like