Search code examples
unity-game-enginescreencenterparentgameobject

How to center parent game object in the screen?


I am trying to make a Scrabble word game using a fixed camera, but I have a simple issue.

I add some boxes as game objects and the number of these boxes is the length of the word so if the word is "Fish" we will add 4 boxes dynamically. I did that successfully, but I can't center those boxes in the screen. I tried to add those game objects as children under another game object, then center the parent, but with no effect.

This is my code:

void Start () {

    for (int i=0; i<word.Length; i++) {
        GameObject LetterSpaceObj = Instantiate(Resources.Load ("LetterSpace", typeof(GameObject))) as GameObject;
        LetterSpaceObj.transform.parent = gameObject.transform;
        LetterSpaceObj.transform.localPosition = new Vector2(i*1.5f,0.0f);
        LetterSpaceObj.name = "LetterSpace-"+count.ToString();  
        count++;
    }

    gameObject.transform.position = new Vector2 (0.0f, 0.0f);

}

This image shows you the idea:

enter image description here


Solution

  • I believe your code is working, but the problem is that your first letter is located at your parent object, and then every letter from then on is added to the right. That means that when you center the parent object what you are doing is putting the first letter in the center of the screen.

    If you run the game and use the scene view to look at where the parent object is this can confirm this. What you can do instead is that rather than placing the parent at the center of the screen, offset it by an amount equal to the length of the word.

    gameObject.transform.position = new Vector2 (-(word.Length / 2.0f) * 1.5f, 0.0f);
    

    You might also want to consider changing some of those constants, such as the 1.5f into variables with names like LetterSize or basing it off the actual prefab so that way any future changes will work automatically.