Search code examples
c#user-interfaceunity-game-engineunity-ui

GridLayout or RectTransform Issues


Right now I'm working on a card game in unity3d and I'm trying to use the Grid Layout Group for the enemy's hand. This works fine if everything is predetermined, however when I try to add a card dynamically to the group the position and size of the cards change. Here's what it should look like : What should happen

And here's what actually happens : Card being (The little brown plank in the center of the screen is the board)

I've got code to try and scale the size and position to what it should be but it doesn't seem to work.

public void AddCardToOppositeHand(Card card)
    {
        GameObject cardUI = Instantiate(UtilFuncs.GetAssetHolder().card);
        cardUI.GetComponent<CardVisible>().LoadCard(card, false);
        cardUI.transform.SetParent(gameObject.transform, true);

        cardUI.GetComponent<RectTransform>().localScale = new Vector3(0.5f, 0.5f, 1);
        cardUI.GetComponent<RectTransform>().position = Vector3.zero;

        Pair<Card, GameObject> pair = new Pair<Card, GameObject>(card, cardUI);
        AddToDictionary(pair);
    }

Does anyone have any ideas? I'm completely stuck on how to fix this, and thanks in advance for any help.


Solution

  • After some work, I've found that looping through the children of the "hand" afterwards and applying the scaling and transforming seems to do it, just not on the object its self. No idea why but here's the code anyways for you guys.

    public void AddCardToOppositeHand(Card card)
        {
            GameObject cardUI = Instantiate(UtilFuncs.GetAssetHolder().card);
            cardUI.GetComponent<CardVisible>().LoadCard(card, true);
            cardUI.transform.SetParent(gameObject.transform, true);
    
            Pair<Card, GameObject> pair = new Pair<Card, GameObject>(card, cardUI);
            AddToDictionary(pair);
    
            reSizeHand();
        }
    
        public void reSizeHand()
        {
            for (int i = 0; i < transform.childCount; i++)
            {
                transform.GetChild(i).GetComponent<RectTransform>().localScale = new Vector3(0.5f, 0.5f, 1);
                transform.GetChild(i).GetComponent<RectTransform>().localPosition = new Vector3(transform.GetChild(i).GetComponent<RectTransform>().localPosition.x, transform.GetChild(i).GetComponent<RectTransform>().localPosition.y, 0);
            }
        }