Search Unity

Instantiate Object with HingeJoint

Discussion in 'Physics' started by Masterchiefs, Feb 1, 2015.

  1. Masterchiefs

    Masterchiefs

    Joined:
    Jan 10, 2015
    Posts:
    20
    Hi guys,

    I have a prefab of a ball that is attached to the player rigidbody by means of a HingeJoint component. The Player is able to move around the x-axis and can shoot whenever he wants. After a short interval, a new ball is instantiated and attached to the player by HingeJoint again.

    Now the problem is that I have created a script to destroy the hingejoint in order for the ball to be able to leave the player.

    Code (CSharp):
    1. void Update()
    2. {
    3. myHingeJoint = GetComponent<HingeJoint> ();
    4.   if (Input.GetKeyDown("space")) {
    5.     Destroy(myHingeJoint);
    6.     Debug.Log("Destroyed");
    7.     rigidbody.velocity = Vector3.up * speed;
    8. }

    Now when I start the game, the first time it is working fine, however when I "shoot" the first ball, the hingeJoint of the next ball that is instantiated is destroyed already when it appears on the screen.

    Any idea on how to fix this?
     
  2. Uberpete

    Uberpete

    Joined:
    Jan 16, 2014
    Posts:
    78
    I'm not sure about your setup but it should work fine.

    If you're using multiple balls in one scene, you ought to check if the ball if first in line to be shot.

    Code (CSharp):
    1. void Update()
    2. {
    3. myHingeJoint = GetComponent<HingeJoint> ();
    4.   if (Input.GetKeyDown("space") && positionInLine == 0) {
    5.     Destroy(myHingeJoint);
    6.     Debug.Log("Destroyed");
    7.     rigidbody.velocity = Vector3.up * speed;
    8. }
    Watch out if you're instantiating from an object in the scene: when you hit "space", you're disabling the hinge joints of anything with that script attached to it. If that's the case, use a prefab instead.