Issues with setting values in custom class
Heyo .. I'm trying to save all object currently in scene. In my concept, I can Instantiate random objects from prefabs array with random rotation. I wanna save objects as custom class:
[Serializable]
public class LevelData
{
public string levelName;
public BlockData[] blockData;
}
[Serializable]
public class BlockData
{
public int blockId;
public string blockName;
public Vector3 blockPos;
public Vector3 blockRot;
}
First class is the one I'm saving - there's levelName and array of all blocks called blockData - that's another custom class with blockId (array index from prefabs array) and vector3 for position and rotation.
I've already created object of LevelData class as follows:
public LevelData levelData;
Then when "block gathering" is triggered ... array foundBlocks is populated with all the blocks with given tag and levelData.blockData is set to be as big as foundBlocks array is. Then I'm setting these blocks into levelData.blockData array:
for(int i = 0; i < foundBlocks.Length; i++)
{
Debug.Log("Writing " + i + " element");
levelData.blockData[i].blockId = blockNameToArray[foundBlocks[i].name];
levelData.blockData[i].blockName = foundBlocks[i].name;
levelData.blockData[i].blockPos = foundBlocks[i].transform.position;
levelData.blockData[i].blockRot = foundBlocks[i].transform.eulerAngles;
Debug.Log(i + " done");
}
And there's a problem: when setting blockData[i].blockId, it throws NullReferenceException:
NullReferenceException: Object reference not set to an instance of an object
LevelEditor.FindLevelBlocks () (at Assets/LevelEditor.cs:90)
LevelEditor+<SaveToFileEn>d__9.MoveNext () (at Assets/LevelEditor.cs:135)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <3dc54541a2574ac7826a004a212a4332>:0)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
LevelEditor:SaveToFile(Boolean) (at Assets/LevelEditor.cs:119)
UnityEngine.EventSystems.EventSystem:Update() (at C:/Unity/Editor/2019.4.0f1/Editor/Data/Resources/PackageManager/BuiltInPackages/com.unity.ugui/Runtime/EventSystem/EventSystem.cs:377)
So first I thought it could be problem was usage of dictionary (just to "convert" block's name to prefab array index), but it still throws this exception even with fixed ID value. I'm not 100% sure, but inicialization of blockData array could not be a problem, coz it's just fine in the inspector even with right number of elements.
Must be mentioned that it sometimes worked - randomly, now it's not working at all .. So could someone point me in right direction?
Your answer
Follow this Question
Related Questions
How to modify a 2d array [,] of a class? 1 Answer
Save a custom Class Array 0 Answers
Unity custom class array serialization issue. 0 Answers
Null Reference exception with custom class object 0 Answers
How can i fix the null reference? 1 Answer