Friday, 15 January 2010

Unity3D-C# array initialization and population: Null Reference - Object reference not set -



Unity3D-C# array initialization and population: Null Reference - Object reference not set -

i'm trying save game data. @ point of 'copy game info serializable class objects' i'm having issue. here code:

public static void save() { // set save file . . // import game info serializable class playerdata info = new playerdata(); gameobject[] tiles = gameobject.findgameobjectswithtag("tile"); int = 0; print (data.tiles.length); // prints expected (initialization in constructor) foreach(gameobject tile in tiles) { data.tiles[i].x = tile.getcomponent<tilescript>().x; ^^^^^^^^^^^^^^^ //null reference: object reference not set instance of object i++; } . . . print ("game saved!"); }

and here class i'm trying save game info into:

[serializable] class playerdata { public class building { public int index; } public class tile { public int x,y; . . } public tile[] tiles; public playerdata() { tiles = new tile[40]; } }

i cannot locate error make. there special case [serializable] class fellow member initialization? create error , how can prepare it?

each element of tiles initialized default value of tile. if tile reference-type (i.e., class rather struct), null. in add-on creating array, need initialize each element new tile object:

public tile[] tiles; public playerdata() { tiles = new tile[40]; (int = 0; < tiles.length; i++) tiles[i] = new tile(); }

when don't , seek access info at:

data.tiles[i].x

data.tiles[i] homecoming null. attempting access x fellow member on null reference naturally throws nullreferenceexception.

c# arrays unity3d nullreferenceexception

No comments:

Post a Comment