Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to get layout of VisualElement via script?

Discussion in 'Scripting' started by SokolarGm, Oct 8, 2023.

  1. SokolarGm

    SokolarGm

    Joined:
    Feb 8, 2021
    Posts:
    3
    so my element looks like this, and I need to somehow get the layout of each child of #Container element

    My script looks like this
    Code (CSharp):
    1.  
    2. public VisualTreeAsset visualTreeAsset;
    3.     public VisualElement visualElement;
    4.  
    5.     void Start()
    6.     {
    7.         VisualElement rootElement = visualTreeAsset.CloneTree();
    8.  
    9.         var panel = rootElement.Q<VisualElement>("Container");
    10.  
    11.         foreach (var blockElement in panel.Children())
    12.         {
    13.           Debug.Log("X: " + blockElement.layout.x + ", " + "Y: " + blockElement.layout.y);
    14.         }
    15.     }
    16.  
    but as a result I get this


    What am I doing wrong? Help please
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    4,019
    Be sure to print out an identifier for each element, ideally the name or "hashtag", so you know what kind of element you are printing this info for.

    It's probably easiest to just set a breakpoint on the Debug line. Then inspect the blockElement in the IDE to find the property you are looking for.

    I know I always got confused because at runtime you have to go through the style property to get desired style settings, not the root.

    But ... I think the issue is different here. Perhaps you need to log this at a later time because in Start the visual tree may not have performed any layouting yet thus all layout values are still uninitialized (0). Try logging in LateUpdate to verify that assumption.