Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Why is this script causing a text in prefab to dissapear?

Discussion in 'UGUI & TextMesh Pro' started by MartinLukavec, Mar 1, 2024.

  1. MartinLukavec

    MartinLukavec

    Joined:
    Aug 31, 2020
    Posts:
    10
    Hello,
    I was recently trying to make a grid layout that will resize to fit any screen. The grid layout contains a list of prefabs. The prefabs are basically gray rectangles with a text childs. I created a simple script fot it, but I have a problem, that it works only in the editor and stops working when I build and run the game. By "stops working", I mean it still scales correctly, but the prefabs show only as a gray rectangle without the text.
    This is my script:
    Code (CSharp):
    1. RectTransform rectT;
    2.     GridLayoutGroup layout;
    3.  
    4.     // Start is called before the first frame update
    5.     void Start()
    6.     {
    7.         rectT = this.GetComponent<RectTransform>();
    8.         layout = this.GetComponent<GridLayoutGroup>();
    9.     }
    10.  
    11.     // Update is called once per frame
    12.     void Update()
    13.     {
    14.         Rect rect = rectT.rect;
    15.         float width = (rect.width + layout.spacing.x) / Mathf.Round((rect.width + layout.spacing.x) / (150 + layout.spacing.x)) - layout.spacing.x;
    16.         layout.cellSize = new Vector2(width, width);
    17.  
    18.     }
    I also tried to change the Vector2 to `new Vector2(100, 100)` and it works (but obviously doesn't scale correctly). I tried then changing it to `new Vector2(100 + width * 0, 100 + width * 0)`, so I am basically just adding 0 to it, but it stops working again. Any ideas how to solve it?

    (this is the broken standalone build)
    upload_2024-3-1_21-10-27.png

    (this is how it should work)
    upload_2024-3-1_21-8-44.png

    (and this is how it looks out of the play mode)
    upload_2024-3-1_21-7-32.png