In the editor's hierarchy, if I drag and drop one object onto another, the second becomes the parent of the first, and moving the parent will cause the child to move. I see I can set this relationship in code by setting the transform.parent property. So I wrote a component to help with doing that from code:

public class ParentTo: MonoBehaviour
    public GameObject _parent;

    public GameObject Parent {
        get { return _parent; }
        set {
            this.transform.parent = value.transform;
            this._parent = value;
            Debug.Log("Set parent");

So to test it, I have 2 cubes in the scene. On cube 2 I put the ParentTo script, leaving it with no parent set, then start the game and use the editor to drop Cube 1 on that field in the inspector. According to the inspector, it seems to have been set right, but the debug statement doesn't appear in the console and moving Cube 1 doesn't move Cube 2. What am I doing wrong?

  • \$\begingroup\$ Hi, do you call method parent of your script? \$\endgroup\$ – NorbyAriel Nov 30 '19 at 21:26
  • \$\begingroup\$ In other code? No, I thought assigning the parent in the inspector would hit the setter. Is that the issue? \$\endgroup\$ – user134167 Nov 30 '19 at 23:07
  • \$\begingroup\$ Comment the method code, save and return to the unity inspector and verify, you should continue to see the variable "Parenst" to assign \$\endgroup\$ – NorbyAriel Dec 3 '19 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.