Search Unity

Question Change TextMesh Pro Child

Discussion in 'Scripting' started by dudironimis, Apr 10, 2021.

  1. dudironimis

    dudironimis

    Joined:
    Apr 10, 2021
    Posts:
    7
    For my first unity project, I'm creating a sudoku. I have canvas that has 81 images as its children. The 81 images are white squares with black borders to create a sudoku board. Each one of those images also have a TextMesh Pro child.

    What I'm now trying to do is write code that changes the text of the TextMesh Pro within each of those boxes.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,752
    Put the TextMeshPRO items into a GridLayoutGroup, keep track of each one in a 2D array, then get at them that way.

    I would make a UI GridLayoutGroup that is 9x9 in size and emplace ONE digit in there.

    Then at runtime you would take that one digit and clone it 80 times (so now you have 81 of them).

    Each time you clone that digit, put a reference to it (either the GameObject or the TextMeshPRO object under it) into your 2D array.

    Now you can go ahead and use that to present the internal contents of the game's logic state.
     
  3. dudironimis

    dudironimis

    Joined:
    Apr 10, 2021
    Posts:
    7
    Is there a way to make the grid uneven? Currently I have a very stylized board.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,752
    You could get the source for the GridLayoutGroup and either subclass or hack it to do whatever shape function you like as it flows stuff.

    Or you can just flow stuff in an 9x9 pattern relative to another parent RectTransform, keep it simple.

    Another neat workflow technique: make the GridLayoutGroup as you did now, insert all the tiles into it (81 tiles).

    Now remove the GridLayoutGroup component... voila, all the tiles are still where you want them.

    Now you have a start and can move them around and save the scene.
     
  5. dudironimis

    dudironimis

    Joined:
    Apr 10, 2021
    Posts:
    7

    I cannot for the life of me figure out how to get the TMP to do ANYTHING with code.

    with the code:
    Code (CSharp):
    1.     TMP_Text nums = GetComponent<TMP_Text>();
    2.        
    3.  nums.text = "2";
    or

    Code (CSharp):
    1. TextMeshProUGUI nums = gameObject.GetComponent<TextMeshProUGUI>();
    2.        
    3.         nums.text = "2";
    I get the "Object reference not set to an instance of an object" error.
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,752
    This only works if those objects are ON this same GameObject.

    Until you get handy with this stuff, it's always best to create public references in your script and actually drag the desired text-ish object in and access it that way.