Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Can't AddForce to Insantiated Object

Discussion in '2D' started by like_a_bosss, Apr 4, 2015.

?

what is the reason it does not work

  1. unity api has changed

    0 vote(s)
    0.0%
  2. diffrent reason

    0 vote(s)
    0.0%
  1. like_a_bosss

    like_a_bosss

    Joined:
    Mar 18, 2015
    Posts:
    56
    Hi my prefab has RigidBody2d and Collider2D attached
    I try to instantiate that prefab and initial force(ennemy's bullet)
    but i dont see any Force effect on the instantiated object.
    Could sombody take a quick look?


    Code (JavaScript):
    1.  
    2. function FixedUpdate(){shoot();}
    3.  
    4.  
    5. function shoot(){
    6. if(ready_to_shoot){ready_to_shoot=false;
    7.                        
    8.                          var arrr= Instantiate(trol_arrow, miejste_strzaly.position, miejste_strzaly.rotation );
    9.                          arrr.GetComponent.<Rigidbody2D>().AddForce(Vector3(10,0,0));
    10. yield WaitForSeconds(1);
    11. ready_to_shoot=true;
    12.  
    13. }}              
    14.        
     
  2. Jananton

    Jananton

    Joined:
    Oct 8, 2014
    Posts:
    22
    Hmm, I have the feeling there's quite a lot wrong with the above code, even with my noob eyes. ;-)
    First I'm 99.99% percent certain AddForce needs a new Vector3() and since it's used with a Rigidbody2D I think a Vector2() would probably suffice.

    Second, a yield construction won't work in a normal function, you need an IEnumerator for that to work and the correct syntax would then be: yield return new WaitForSeconds(1);

    Third, for something used often like the call AddForce on the Rigidbody2D of the arrow you should better create a private variable rigidbody that you instantiate in the Start() function from the arrow game object and use that in the shoot() function instead.

    Greets,

    Jan
     
  3. like_a_bosss

    like_a_bosss

    Joined:
    Mar 18, 2015
    Posts:
    56
    in JS "
    1. yield WaitForSeconds(1);" works just fine- besides ints not in function FixedUpdate. it is inside shoot();

      and after some tweaking it started to work
      Code (JavaScript):
      1. function shoot(){
      2. if(ready_to_shoot){ready_to_shoot=false;
      3.                        
      4.                          var arrr= Instantiate(trol_arrow, miejste_strzaly.position, miejste_strzaly.rotation );
      5.                          arrr.GetComponent.<Rigidbody2D>().AddForce(miejste_strzaly.forward*500);
      6. yield WaitForSeconds(1);
      7. ready_to_shoot=true;
      8.  
      9. }}                

      thx for you intrest :)