Search Unity

Cannot set the parent of the object!!

Discussion in 'Physics' started by gtxnero1, Sep 10, 2016.

  1. gtxnero1

    gtxnero1

    Joined:
    Sep 10, 2016
    Posts:
    3
    Hi guys,

    This bug is doing my head in and I can't figure it out!

    I have an empty gun, and when I move it near the magazine it has a collide trigger that grabs the magazine, scales it and inserts it into the gun. This bit works fine. However in the code i also set the magazine parent to the gun and set the gravity to false and isKinematic to true - these bits do not happen. Therefore the magazine scales to the gun and then floats off into the distance and when I look in Unity it is not set to be a child of the gun and gravity and kinematic are both unchecked even though I clearly set these below. How is the magazine being scaled and positioned correctly but the parent and rigidbody edits are not being made?

    Here is the code:

    1. //THIS CLASS IS A CHILD OF THE GUN
    2. public class GunBody : MonoBehaviour {

    3. void OnTriggerEnter(Collider collider)
    4. {
    5. Debug.LogError("collision with well");

    6. //check if the collision was with the magazine
    7. if (collider.gameObject.name == "Magazine 1")
    8. {
    9. //reload the gun if it was
    10. addClip(collider.gameObject);
    11. }
    12. }

    13. public void addClip(GameObject magazine)
    14. {
    15. magazine.transform.parent = transform.parent; //DOES NOT WORK
    16. magazine.transform.position = transform.parent.position;
    17. magazine.transform.rotation = transform.parent.rotation;
    18. magazine.transform.localRotation = Quaternion.Euler(-89.96101f, 0f, 0f);
    19. magazine.transform.localScale = new Vector3(14f, 20f, 20f);
    20. magazine.transform.localPosition = new Vector3(0f, -0.8215461f, 1.64772f);
    21. magazine.GetComponent<Rigidbody>().useGravity = false; //DOES NOT WORK
    22. magazine.GetComponent<Rigidbody>().isKinematic = true; //DOES NOT WORK
    23. }

    Hopefully someone can spot what is going wrong?

    Thanks
     
  2. Hyblademin

    Hyblademin

    Joined:
    Oct 14, 2013
    Posts:
    725
    Can you take those three statements and put them anywhere, and they won't work still?

    Is it possible that there's another script setting those values?

    Is the magazine's collider in a child object to the magazine? What about the Rigidbody? That could cause some unexpected behavior.
     
  3. dudester

    dudester

    Joined:
    Oct 25, 2014
    Posts:
    371
    i think maybe you want to use magazine.transform.parent = transform
    not magazine.transform.parent = transform.parent