- Home /
Object after instantiate doesn't apply AddForce
Hello, I was instantiating a prefab by UnityOfficial tutorial for Instantiate. All work except "AddForce" command. I wrote script as in the tutorial, but variable ballPrefab I made as GameObject type instead of Rigidbody. If it is Rigidbody, I can not add prefab in the inspector into it... Here is the code:
 public Transform spawner;
 public GameObject ballPrefab;
 
 void Update () {
         
         if (Input.GetButtonDown("Fire1")) {
 
            Rigidbody ballInstance;
            ballInstance = Instantiate(ballPrefab, spawner.transform.position, spawner.rotation) as Rigidbody;
 
            ballInstance.AddForce(spawner.forward * 3000);
         }
 }
Thanks for advices guys. Roberthu could you make your post as answer? I would mark it as correct.
Answer by robertbu · Oct 19, 2013 at 09:19 PM
Try it this way:
 public Transform spawner;
 public GameObject ballPrefab;
  
 void Update () {
  
         if (Input.GetButtonDown("Fire1")) {
  
            GameObject ballInstance;
            ballInstance = Instantiate(ballPrefab, spawner.transform.position, spawner.rotation) as GameObject;
  
            ballInstance.rigidbody.AddForce(spawner.forward * 3000);
         }
 }
Thank you so much for this. The documentation from Unity is not very well worded for AddForce.
The problem was not the AddForce(). The issue is that 'ballPrefab' is a GameObject, but you cast it to a Rigidbody. It will work when both the 'ballPrefab' and the 'ballInstance' are the same type...either Rigidbody or GameObject.
I have already used Rigidbody2D for my 2D game but then also force is not being applied. Can you give me a solution?
How could we know what you are trying to do with this amount of information?
Your answer
 
 
             Follow this Question
Related Questions
instantiating vertically 2 Answers
Instantiation in C# 1 Answer
How to make TCG Deck (Instatiate based on Prefab) 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                