NullReferenceException when accessing to an element of array from another script
I have two objects: Tile and TileGrid which have their own scripts.
TileGrid can generate a 2d array of Tiles. Then I am trying to attach every Tile around the Tile in the script for every Tile, so all of my Tiles will have a reference to their 'neighbors'. I use a dictionary.
To do that I wrote a function which is accessing TileGrid's 2d array of Tiles.
Unfortunately, a NullReferenceException is thrown.
TileGridScript.cs
public class TileGridScript : MonoBehaviour
{
public GameObject tileGrid;
// Other properties ...
public void MakeGrid(int width = 64, int height = 64)
{
tileGrid = new GameObject[width];
for (int x = 0; x < width; x++)
{
tileGrid[x] = new GameObject[height];
for (int y = 0; y < height; y++)
{
// !!! Instantiating tiles !!!
tileGrid[x][y] = Instantiate(grassPrefab, new Vector2(x - width / 2, y - height / 2), Quaternion.identity);
}
}
// !!! Call the function to connect Tiles !!!
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
tileGrid[x][y].GetComponent<TileScript>().AttchTile(this);
}
}
TileScript.cs
public class TileScript : MonoBehaviour
{
public Dictionary<string, GameObject> connectedTiles;
// Other properties ...
private void Start()
{
connectedTiles = new Dictionary<string, GameObject>(8);
}
public void AttchTile (TileGridScript tileGridScript)
{
for (int biasx = -1; biasx < 2; biasx++)
{
for (int biasy = -1; biasy < 2; biasy++)
{
switch (biasx)
{
case -1: // L
switch (biasy)
{
case -1: // D
try
{
// !!! Catches the error here !!!
connectedTiles["DL"] = tileGridScript.tileGrid[(int)position.x + biasx][(int)position.y + biasy];
}
catch (System.IndexOutOfRangeException) { }
break;
}
// etc for every Tile. P.S. DL means Down and Left.
// in this way I add all 8 Tiles around that
}
}
}
}
}
GameManager.cs
public class GameManager : MonoBehaviour
{
public GameObject tileGridPrefab;
// Other properties...
void Start()
{
// !!! Here I generate the Tile Grid !!!
tileGridPrefab.GetComponent<TileGridScript>().MakeGrid(24, 16);
}
}
I tried to write this function in TileGrid's script and call it from that.
If I don't initialize a dictionary in Start() it does okay. Then when I access it from another script, it falls with the same error.
I tried to change the order of these scripts in the editor.
What is the reason for the problem and how can I fix it?
c# arrays unity3d nullreferenceexception gameobject
add a comment |
I have two objects: Tile and TileGrid which have their own scripts.
TileGrid can generate a 2d array of Tiles. Then I am trying to attach every Tile around the Tile in the script for every Tile, so all of my Tiles will have a reference to their 'neighbors'. I use a dictionary.
To do that I wrote a function which is accessing TileGrid's 2d array of Tiles.
Unfortunately, a NullReferenceException is thrown.
TileGridScript.cs
public class TileGridScript : MonoBehaviour
{
public GameObject tileGrid;
// Other properties ...
public void MakeGrid(int width = 64, int height = 64)
{
tileGrid = new GameObject[width];
for (int x = 0; x < width; x++)
{
tileGrid[x] = new GameObject[height];
for (int y = 0; y < height; y++)
{
// !!! Instantiating tiles !!!
tileGrid[x][y] = Instantiate(grassPrefab, new Vector2(x - width / 2, y - height / 2), Quaternion.identity);
}
}
// !!! Call the function to connect Tiles !!!
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
tileGrid[x][y].GetComponent<TileScript>().AttchTile(this);
}
}
TileScript.cs
public class TileScript : MonoBehaviour
{
public Dictionary<string, GameObject> connectedTiles;
// Other properties ...
private void Start()
{
connectedTiles = new Dictionary<string, GameObject>(8);
}
public void AttchTile (TileGridScript tileGridScript)
{
for (int biasx = -1; biasx < 2; biasx++)
{
for (int biasy = -1; biasy < 2; biasy++)
{
switch (biasx)
{
case -1: // L
switch (biasy)
{
case -1: // D
try
{
// !!! Catches the error here !!!
connectedTiles["DL"] = tileGridScript.tileGrid[(int)position.x + biasx][(int)position.y + biasy];
}
catch (System.IndexOutOfRangeException) { }
break;
}
// etc for every Tile. P.S. DL means Down and Left.
// in this way I add all 8 Tiles around that
}
}
}
}
}
GameManager.cs
public class GameManager : MonoBehaviour
{
public GameObject tileGridPrefab;
// Other properties...
void Start()
{
// !!! Here I generate the Tile Grid !!!
tileGridPrefab.GetComponent<TileGridScript>().MakeGrid(24, 16);
}
}
I tried to write this function in TileGrid's script and call it from that.
If I don't initialize a dictionary in Start() it does okay. Then when I access it from another script, it falls with the same error.
I tried to change the order of these scripts in the editor.
What is the reason for the problem and how can I fix it?
c# arrays unity3d nullreferenceexception gameobject
HereconnectedTiles["DL"] = tileGridScript.tileGrid[(int)position.x + biasx][(int)position.y + biasy];. I added a comment there. Of course I know what it is. But I don't understand why I get it.
– Keyshon
Dec 31 '18 at 4:12
As you can see from my code, I initialize all Tiles in the array before calling the attach function. Still I get this exception.
– Keyshon
Dec 31 '18 at 4:15
add a comment |
I have two objects: Tile and TileGrid which have their own scripts.
TileGrid can generate a 2d array of Tiles. Then I am trying to attach every Tile around the Tile in the script for every Tile, so all of my Tiles will have a reference to their 'neighbors'. I use a dictionary.
To do that I wrote a function which is accessing TileGrid's 2d array of Tiles.
Unfortunately, a NullReferenceException is thrown.
TileGridScript.cs
public class TileGridScript : MonoBehaviour
{
public GameObject tileGrid;
// Other properties ...
public void MakeGrid(int width = 64, int height = 64)
{
tileGrid = new GameObject[width];
for (int x = 0; x < width; x++)
{
tileGrid[x] = new GameObject[height];
for (int y = 0; y < height; y++)
{
// !!! Instantiating tiles !!!
tileGrid[x][y] = Instantiate(grassPrefab, new Vector2(x - width / 2, y - height / 2), Quaternion.identity);
}
}
// !!! Call the function to connect Tiles !!!
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
tileGrid[x][y].GetComponent<TileScript>().AttchTile(this);
}
}
TileScript.cs
public class TileScript : MonoBehaviour
{
public Dictionary<string, GameObject> connectedTiles;
// Other properties ...
private void Start()
{
connectedTiles = new Dictionary<string, GameObject>(8);
}
public void AttchTile (TileGridScript tileGridScript)
{
for (int biasx = -1; biasx < 2; biasx++)
{
for (int biasy = -1; biasy < 2; biasy++)
{
switch (biasx)
{
case -1: // L
switch (biasy)
{
case -1: // D
try
{
// !!! Catches the error here !!!
connectedTiles["DL"] = tileGridScript.tileGrid[(int)position.x + biasx][(int)position.y + biasy];
}
catch (System.IndexOutOfRangeException) { }
break;
}
// etc for every Tile. P.S. DL means Down and Left.
// in this way I add all 8 Tiles around that
}
}
}
}
}
GameManager.cs
public class GameManager : MonoBehaviour
{
public GameObject tileGridPrefab;
// Other properties...
void Start()
{
// !!! Here I generate the Tile Grid !!!
tileGridPrefab.GetComponent<TileGridScript>().MakeGrid(24, 16);
}
}
I tried to write this function in TileGrid's script and call it from that.
If I don't initialize a dictionary in Start() it does okay. Then when I access it from another script, it falls with the same error.
I tried to change the order of these scripts in the editor.
What is the reason for the problem and how can I fix it?
c# arrays unity3d nullreferenceexception gameobject
I have two objects: Tile and TileGrid which have their own scripts.
TileGrid can generate a 2d array of Tiles. Then I am trying to attach every Tile around the Tile in the script for every Tile, so all of my Tiles will have a reference to their 'neighbors'. I use a dictionary.
To do that I wrote a function which is accessing TileGrid's 2d array of Tiles.
Unfortunately, a NullReferenceException is thrown.
TileGridScript.cs
public class TileGridScript : MonoBehaviour
{
public GameObject tileGrid;
// Other properties ...
public void MakeGrid(int width = 64, int height = 64)
{
tileGrid = new GameObject[width];
for (int x = 0; x < width; x++)
{
tileGrid[x] = new GameObject[height];
for (int y = 0; y < height; y++)
{
// !!! Instantiating tiles !!!
tileGrid[x][y] = Instantiate(grassPrefab, new Vector2(x - width / 2, y - height / 2), Quaternion.identity);
}
}
// !!! Call the function to connect Tiles !!!
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
tileGrid[x][y].GetComponent<TileScript>().AttchTile(this);
}
}
TileScript.cs
public class TileScript : MonoBehaviour
{
public Dictionary<string, GameObject> connectedTiles;
// Other properties ...
private void Start()
{
connectedTiles = new Dictionary<string, GameObject>(8);
}
public void AttchTile (TileGridScript tileGridScript)
{
for (int biasx = -1; biasx < 2; biasx++)
{
for (int biasy = -1; biasy < 2; biasy++)
{
switch (biasx)
{
case -1: // L
switch (biasy)
{
case -1: // D
try
{
// !!! Catches the error here !!!
connectedTiles["DL"] = tileGridScript.tileGrid[(int)position.x + biasx][(int)position.y + biasy];
}
catch (System.IndexOutOfRangeException) { }
break;
}
// etc for every Tile. P.S. DL means Down and Left.
// in this way I add all 8 Tiles around that
}
}
}
}
}
GameManager.cs
public class GameManager : MonoBehaviour
{
public GameObject tileGridPrefab;
// Other properties...
void Start()
{
// !!! Here I generate the Tile Grid !!!
tileGridPrefab.GetComponent<TileGridScript>().MakeGrid(24, 16);
}
}
I tried to write this function in TileGrid's script and call it from that.
If I don't initialize a dictionary in Start() it does okay. Then when I access it from another script, it falls with the same error.
I tried to change the order of these scripts in the editor.
What is the reason for the problem and how can I fix it?
c# arrays unity3d nullreferenceexception gameobject
c# arrays unity3d nullreferenceexception gameobject
edited Dec 31 '18 at 8:38
Embodiment of Ignorance
25619
25619
asked Dec 31 '18 at 3:24
KeyshonKeyshon
104
104
HereconnectedTiles["DL"] = tileGridScript.tileGrid[(int)position.x + biasx][(int)position.y + biasy];. I added a comment there. Of course I know what it is. But I don't understand why I get it.
– Keyshon
Dec 31 '18 at 4:12
As you can see from my code, I initialize all Tiles in the array before calling the attach function. Still I get this exception.
– Keyshon
Dec 31 '18 at 4:15
add a comment |
HereconnectedTiles["DL"] = tileGridScript.tileGrid[(int)position.x + biasx][(int)position.y + biasy];. I added a comment there. Of course I know what it is. But I don't understand why I get it.
– Keyshon
Dec 31 '18 at 4:12
As you can see from my code, I initialize all Tiles in the array before calling the attach function. Still I get this exception.
– Keyshon
Dec 31 '18 at 4:15
Here
connectedTiles["DL"] = tileGridScript.tileGrid[(int)position.x + biasx][(int)position.y + biasy];. I added a comment there. Of course I know what it is. But I don't understand why I get it.– Keyshon
Dec 31 '18 at 4:12
Here
connectedTiles["DL"] = tileGridScript.tileGrid[(int)position.x + biasx][(int)position.y + biasy];. I added a comment there. Of course I know what it is. But I don't understand why I get it.– Keyshon
Dec 31 '18 at 4:12
As you can see from my code, I initialize all Tiles in the array before calling the attach function. Still I get this exception.
– Keyshon
Dec 31 '18 at 4:15
As you can see from my code, I initialize all Tiles in the array before calling the attach function. Still I get this exception.
– Keyshon
Dec 31 '18 at 4:15
add a comment |
1 Answer
1
active
oldest
votes
The problem is that Start() is calling after AttachTile().
I should use Awake() instead. I get TileGrid object in Awake() and then can use it in AttachTile() function.
Very typical example for a race condition .. I use a simple rule: Whatever only depends on me (e.g. getting components, setting default values etc) do inAwake; whatever depends on other components, objects etc do inStart
– derHugo
Dec 31 '18 at 12:03
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53983290%2fnullreferenceexception-when-accessing-to-an-element-of-array-from-another-script%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
The problem is that Start() is calling after AttachTile().
I should use Awake() instead. I get TileGrid object in Awake() and then can use it in AttachTile() function.
Very typical example for a race condition .. I use a simple rule: Whatever only depends on me (e.g. getting components, setting default values etc) do inAwake; whatever depends on other components, objects etc do inStart
– derHugo
Dec 31 '18 at 12:03
add a comment |
The problem is that Start() is calling after AttachTile().
I should use Awake() instead. I get TileGrid object in Awake() and then can use it in AttachTile() function.
Very typical example for a race condition .. I use a simple rule: Whatever only depends on me (e.g. getting components, setting default values etc) do inAwake; whatever depends on other components, objects etc do inStart
– derHugo
Dec 31 '18 at 12:03
add a comment |
The problem is that Start() is calling after AttachTile().
I should use Awake() instead. I get TileGrid object in Awake() and then can use it in AttachTile() function.
The problem is that Start() is calling after AttachTile().
I should use Awake() instead. I get TileGrid object in Awake() and then can use it in AttachTile() function.
answered Dec 31 '18 at 4:41
KeyshonKeyshon
104
104
Very typical example for a race condition .. I use a simple rule: Whatever only depends on me (e.g. getting components, setting default values etc) do inAwake; whatever depends on other components, objects etc do inStart
– derHugo
Dec 31 '18 at 12:03
add a comment |
Very typical example for a race condition .. I use a simple rule: Whatever only depends on me (e.g. getting components, setting default values etc) do inAwake; whatever depends on other components, objects etc do inStart
– derHugo
Dec 31 '18 at 12:03
Very typical example for a race condition .. I use a simple rule: Whatever only depends on me (e.g. getting components, setting default values etc) do in
Awake; whatever depends on other components, objects etc do in Start– derHugo
Dec 31 '18 at 12:03
Very typical example for a race condition .. I use a simple rule: Whatever only depends on me (e.g. getting components, setting default values etc) do in
Awake; whatever depends on other components, objects etc do in Start– derHugo
Dec 31 '18 at 12:03
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53983290%2fnullreferenceexception-when-accessing-to-an-element-of-array-from-another-script%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Here
connectedTiles["DL"] = tileGridScript.tileGrid[(int)position.x + biasx][(int)position.y + biasy];. I added a comment there. Of course I know what it is. But I don't understand why I get it.– Keyshon
Dec 31 '18 at 4:12
As you can see from my code, I initialize all Tiles in the array before calling the attach function. Still I get this exception.
– Keyshon
Dec 31 '18 at 4:15