I'm working on a crossword puzzle game. In order to set the letters in my tiles, I have a script attached to text components that accessing a char array that stores my letters. It looks like this:

First class:

  public class GenerateBoard : MonoBehaviour
    public static char[,]gameBoard = new char[15,15];
    void Start()
        gameBoard[0, 0] = 'W';

Second class:

public class SetLetter : MonoBehaviour
    Text letter;
    public int x;
    public int y;
    // Start is called before the first frame update
    void Start()
        letter = GetComponent<Text>();
        letter.text = GenerateBoard.gameBoard[x,y] + "";

    // Update is called once per frame
    void Update()
        Debug.Log("glitch: " + GenerateBoard.gameBoard[0, 0]);

I would expect Debug.Log to print 'W' but it appears to be empty. Why isn't it accessing the letter 'W' from the first class? When I use Debug.Log in my first class it properly prints 'W'.

  • \$\begingroup\$ Did you create the gameobject before running the script with the log? Also, why does it have to be a static char array? Just pass the board component from the gameobject around using the editor \$\endgroup\$ – Bálint Apr 14 '19 at 23:15
  • \$\begingroup\$ Both scripts are run as soon as the game is started. But because Debug.Log is in update I figured it would be ran after gameBoard had been instantiated... How could I pass a component using the editor? \$\endgroup\$ – Griffin Hines Apr 14 '19 at 23:24
  • \$\begingroup\$ You can use public variables inside behaviours and assign the game objects to them from the editor \$\endgroup\$ – Bálint Apr 14 '19 at 23:29
  • \$\begingroup\$ Yes @GriffinHines Both scripts run as soon as the game started but Script order is a big thing in Unity, Probably the Second Script has a higher script order so the Debug.Log gets called before the first script gets the chance to initialized, Here I am assuming you also attached the first script to GameObject as well \$\endgroup\$ – Digvijaysinh Gohil Apr 15 '19 at 6:19
  • \$\begingroup\$ Have you reviewed existing questions about ensuring an initialization runs before its values are used, so that they have the desired values already when you try to access them? \$\endgroup\$ – DMGregory Apr 25 '19 at 19:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.