- Home /
How to use AddForce() on an Instantiated prefab?
I am instantatiating a projectile prefab using this code:
Instantiate (arrow, bow.transform.position, this.transform.rotation);
However, when I use:
arrow.rigidbody2D.AddForce (thisproj.transform.forward * shootforce);
It doesn't work. I figured it's because Unity thinks I am adding force to the actual prefab and not the clone so I tried doing this:
protected GameObject thisproj;
thisproj = Instantiate (arrow, bow.transform.position, this.transform.rotation);
and then :
thisproj.rigidbody2D.AddForce (thisproj.transform.forward * shootforce);
however apparently, Instantiate() returns an Object not GameObject. But, I can't figure out how to use AddForce() on an Object or get Instantiate() to return a GameObject.
Thank You!
Forget the AddForce part. As you wrote, you just need to get the new object as a Transform or GameObject in order to do [some thing] to it.
$$anonymous$$any, many, many examples of doing that on this site. Sure, roberto's answer works. But in general, if you narrow things down to the actual problem, the answer is already here.
Answer by robertbu · Aug 30, 2014 at 04:38 AM
Just cast it:
GameObject thisproj = Instantiate (arrow, bow.transform.position, this.transform.rotation) as GameObject;
thisproj.rigidbody2D.AddForce (thisproj.transform.forward * shootforce);
Note using 'thisproj.transform.forward' is not often found in 2D games. If 'arrow' is a sprite, you likely want 'thisproj.transform.right' or possibly 'thisproj.transform.up'.
Your answer
![](https://koobas.hobune.stream/wayback/20220613161854im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Referencing instantiated objects at runtime 2 Answers
getting GameObject from Array and then instantiating 2 Answers
Cannot instantiate gameobject 3 Answers
Reference by Instance ID? 2 Answers