Cannot access 2D array element
Edit2 ^^ That is the code I have, for some reason the editor here is deleting parts of it.
So I've spent a significant amount of time on this issue and I'm wondering if it is a bug or if I'm just flippin nuts.
Okay so I have a 2D array of GameObject tiles with an x of 10 and y of 12. I have the array on a GameManager script on a separate GameObject in the scene. When the game begins a circle is instantiated as a child of one of the gameObjects in the array, thus putting it on that 'space'. The deal is I'm trying to access the GameManager script from the circle's script through a public GameObject variable. This variable is set in the inspector so I should just be able to access the GameManager Script right?
The code I have to access the script is:
public GameManager gameManager;
TileInfo tileInfo = gameManager.tile[topLeftX, topLeftY].transform.GetComponent();
//This always gets a null reference exception.
I'm trying to access the 2D array from the gameManager.
Ultimately I'm looking to: grab a script from the tile, through the gameManager's 2Darray, through a public GameObject in the script that is above.
I'm sorry if this is confusing, I'll put more if you think I need it, I've debugged down to that accessing the gameManager script is the problem.
Thanks!
Answer by EmHuynh · Mar 06, 2016 at 11:18 PM
Hello, @Mr0w3m.
Edit: Maybe, the variable gameManager
is null and not the array, since they've been instantiated. Unless, they were destroyed.
When calling, the GetComponent
function, you need to set its parameter "type" to the type of the component you are trying to reference to. In this case, its TileInfo
. Here is the documentation: Component.GetComponent.
TileInfo tileInfo = gameManager.tile[ topLeftX, topLeftY ].GetComponent< TileInfo >();
I actually typed ();> but it keeps deleting that part in <> because it comes up with a red underline, I don't know how to fix this. Edit1: whatever spellcheck is set up here is deleting parts of my code...
Hello, @$$anonymous$$r0w3m.
Okay, I understand. Thanks for the clarity and for providing an image. $$anonymous$$y answer has been improved. TileInfo tileInfo = game$$anonymous$$anager.GetComponent< TileInfo >().tile[ topLeftX, topLeftY ];
Thank you for the reply, but I'm trying to access the 2D array on the game$$anonymous$$anager, and then access the TileInfo component of a part of the 2D array, not the other way around. I've updated my code so it makes more sense and posted a better structured question herelink text
Hey, @$$anonymous$$r0w3m. Did you initialize the variable, game$$anonymous$$anager
?