Getting a child GameObject to inherit its parent's position

I’m building a card game engine that generates a card library with attributes, text, and images drawn from an external XML file, then creates and shuffles a deck, then draws cards off the top of the deck to form hands for the player and the computer.

So far, so good–but I’ve been running into an issue when I instantiate the actual cards. The Card script instantiates Textfield (the name I’ve given to a TextMesh object within Assets>Resources) children that are meant to display the title and description of the card. However, these objects all appear at the exact same point in the scene, no matter where their Card parents are:

It appears that they aren’t inheriting their parents’ position in the scene. How do I make them do that?

Here’s the relevant function as it exists right now, contained within the CardScript script attached to the Card class:

void addText () {

        Debug.Log("   adding text fields to card" );

        //add title text field
        titleField = Instantiate( Resources.Load( "Textfield" ) , new Vector3(0, 0.01f, 0) , Quaternion.identity ) as GameObject;    //create instance of Textfield

        if ( cardName != null ) {
            titleField.GetComponent<TextMesh>().text = cardName;
        }
    }

you aren’t parenting the text to the card… you need

titleField.SetParent(transform);

after the instantiate line

Aha! You apparently have to call SetParent from the object’s transform property (i.e. it should actually be…

titleField.transform.SetParent( transform );

…but otherwise that seems to have done the trick. Thanks!

huh, yeah that extra step keeps catching me out… :smile:

So, new problem: rather than snapping the Textfield prefabs to the same coordinates as the Card, Unity is placing them at seemingly arbitrary points relative to their parents.

New code:

void addText () {

        Debug.Log("   adding text fields to card" );

        //add title text field
        titleField = Instantiate( Resources.Load( "Textfield" ) , new Vector3(-0.9f, 0.01f, 0) , Quaternion.identity ) as GameObject;    //create instance of Textfield
        titleField.transform.SetParent( transform );

        if ( cardName != null ) {
            titleField.GetComponent<TextMesh>().text = cardName;
        }

        //add casting cost text field
        costField = Instantiate( Resources.Load( "Textfield" ) , new Vector3(0.7f, 0.01f, 0) , Quaternion.identity ) as GameObject;    //create instance of Textfield
        costField.transform.SetParent( transform );

        costField.GetComponent<TextMesh>().text = castingCost.ToString();
    }

New results:

What is going on here?