I’m trying to create a multi-dimensional array that I can edit in the inspector, and was told to use a serializable class containing my array.
This is what I tried:
using UnityEngine;
using System.Collections;
[System.Serializable]
public class MDIntArray
{
public int[] intArray;
}
public class TestScript : MonoBehaviour {
public MDIntArray[] mdIntArr;
int[] ia = mdIntArr[0].intArray;
//print (ia[0]);
}
public class TestScript : MonoBehaviour {
public MDIntArray[] mdIntArr;
int[] ia;
void Start(){
ia = mdIntArr[0].intArray = new int[TheSizeYouNeed];
print (ia[0]);
}
}
This isn’t about serializing or anything- you can’t initialize a variable to a value that’s based on another (non-static) variable in a field initializer. That means that:
int[] ia = mdIntArr[0].intArray;
simply won’t work. I’m sure someone can give an explanation that details compile-time type integrity or some such thing, but if you want to initialize to some variable value in that way, you need to do it in a constructor or an Awake/Start function and not as a field initialization.
Now I have issues with putting the returned item into a int[ ] object
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class MultidimensionalString {
public string[] stringArray = new string[0];
public string this[int index] {
get {
return stringArray[index];
}
set {
stringArray[index] = value;
}
}
public int Length {
get {
return stringArray.Length;
}
}
public long LongLength {
get {
return stringArray.LongLength;
}
}
}
[System.Serializable]
public class MDIntArray
{
public int[] intArray = new int[0];
public int this[int index] {
get {
return intArray[index];
}
set {
intArray[index] = value;
}
}
public int Length {
get {
return intArray.Length;
}
}
public long LongLength {
get {
return intArray.LongLength;
}
}
}
public class TestScript : MonoBehaviour {
public MDIntArray[] mdIntArr = new MDIntArray[0];
int[] intArr;
//int[] ia = mdIntArr[0].intArray;
//print (ia[0]);
public MultidimensionalString[] multidimensional = new MultidimensionalString[0];
public void Start(){
intArr= mdIntArr[0]; //compile error occurs here
print (multidimensional[0][0]);
print (mdIntArr[0][0]);
print (mdIntArr[0].Length);
//Debug.Log(multidimensional[1][1]);
}
}
which, according to the error log, tells me the code is trying to stuff a MDIntArray into the int[ ] object.
EDIT: The solution was just to reference the intArray object: