Editor window two dimensional toggle array

[Sorry for my bad english]
I’m total beginner at editor window scripting and I’m trying to make a two dimensional toggle array in my custom editor window. My problem: When I click a toggle button the true/false value does not change. Is that any sollution for this problem?

The width and height must remain changable.

Here’s my code:

using UnityEngine;
using UnityEditor;
using System.Collections;

public class LevelEditor : EditorWindow {

	bool[,] fieldsArray = new bool[0,0];
	int width = 1;
	int height = 1;
	int levelNumber = 1;
	
	[MenuItem("Window/LevelEditor")]
	public static void ShowWindow()
	{
		EditorWindow.GetWindow(typeof(LevelEditor));
	}
	
	void OnGUI()
	{
		GUILayout.Label ("LEVEL NUMBER", EditorStyles.boldLabel);
		levelNumber = EditorGUILayout.IntField ("Level Number", levelNumber);
		GUILayout.Label ("Array width/height", EditorStyles.boldLabel);
		width = EditorGUILayout.IntField ("Width", width);
		height = EditorGUILayout.IntField ("Width", height);

		fieldsArray = new bool[width, height];
		ChangeArrayWidthAndHeight ();
		if (GUILayout.Button ("Apply")) {
			// applies array to GameManager
		}
	}

	void ChangeArrayWidthAndHeight()
	{
		for (int j=0; j<height; j++) {
			EditorGUILayout.BeginHorizontal();
			for (int i=0; i<width; i++) {
				fieldsArray[i,j] = EditorGUILayout.Toggle(fieldsArray[i,j]);
			}
			EditorGUILayout.EndHorizontal();
		}
	}

}

![1]

This is happening because a new bool[,] is being created every single OnGUI, not just when the width or height changes. Try wrapping it in an if statement:

if (width != fieldsArray.GetLength(0) || height != fieldsArray.GetLength(1)) {
	fieldsArray = new bool[width, height];
}

You can put the array initialization in the ShowWindow function. Be aware, that a 2 dimensional array will not be serialized by Unity. This means, it cannot save the data when starting play mode or closing the editor application. You will have to use a single dimensional array.

To convert from 2 to 1 dimensional arrays use this formula: index = x + y * width;

This is for a Texture Toggle, U can also convert it to GUIContent by changing its parameters.

public bool[,] Array2D;
Texture2D OnImage, OffImage;

void OnGUI()
{
    for (int i = 0; i < Array2D.GetLength(0); i++)
    {
        for (int j = 0; j < Array2D.GetLength(1); j++)
        {
            Array2D[i, j] = GUILayout.Toggle(Array2D[i, j], Array2D[i, j] ? OnImage : OffImage, "Button");
        }
    }
}