How to improve my level creation script?

Hello all,
I created a thread about the low performances of my script to create a level on WebGL:

A I didn’t get any answer, I will change my point of view and ask you how to improve the performances of my script to create level from a matrix.
The following code is not the real one but it explain the processus I use; the matrix is a picture and where I check the color of each cases with a method called GetPixelColor.

void InitLevel()
{
    // Load multi textures
    UnityEngine.Object[] Floors = Resources.LoadAll("Decors/Textures/Floors");
    UnityEngine.Object[] Walls = Resources.LoadAll("Decors/Textures/Walls");

    // Generate the level
    for (int i = 0; i < SizeI; i++)
    {
        for (int j = 0; j < SizeJ; j++)
        {
            Color pixel = GetPixelColor(i, j);
            if (pixel == Color.blue) // add floor
            {
                int MaxNb = 20; // number of different sorts of wall
                int FloorNb = UnityEngine.Random.Range(0, MaxNb) + 1;

                //Calculate position of the wall
                float x = 0.64f * i + 0.64f * j;
                float y = 0.48f * i - 0.48f * j;

                // Load Texture
                UnityEngine.Sprite sprite = Floors[FloorNb] as UnityEngine.Sprite;

                // Create Wall object
                GameObject Floor = new GameObject();
                SpriteRenderer renderer = Floor.AddComponent<SpriteRenderer>();
                renderer.sprite = sprite;
                Floor.transform.position = new Vector3(x, y, 0f);
            }
            else if (pixel == Color.red) // add wall
            {
                int MaxNb = 10; // number of different sorts of wall
                int WallNb = UnityEngine.Random.Range(0, MaxNb) + 1;

                //Calculate position of the wall
                float x = 0.64f * i + 0.64f * j;
                float y = 0.48f * i - 0.48f * j;

                // Load Texture
                UnityEngine.Sprite sprite = Walls[WallNb] as UnityEngine.Sprite;

                // Create Wall object
                GameObject Wall = new GameObject();
                SpriteRenderer renderer = Wall.AddComponent<SpriteRenderer>();
                renderer.sprite = sprite;
                Wall.transform.position = new Vector3(x, y, 0f);
            }
        }
    }
}

It’s pretty difficult to simply guess what is slow in your real code (except for the obvious possibility that the image you’re using to map walls and floors is very large). But I’ll offer a few generic ideas.

Individual pixel color lookups with GetPixel are very slow. Use GetPixels32 to grab all the pixel data into an array in a single call.

Even better, store your maps in a more efficient format. A text file of 0’s and 1’s would load and process more quickly than a bitmap and provide exactly the same information as blue==floor and red==wall.

Better still, write an editor script to generate your map data as a ScriptableObject and load that at runtime.

Perhaps best of all, if you can pre-process your data to produce a ScriptableObject, you could actually write an editor script to create the level, then store that level data as a prefab in the AssetDatabase, and at runtime your level loading operation would take just a couple of lines of code.

Thanks for the answer!
I agree that the GetPixel could be one of the cause of the performance issues… I used it because it’s very easy to create a level using color code and as I didn’t saw any performance issues on editor/android, I didn’t change it.
I will try to add debug information to calculate the process time of each operation to see where is the problem.
I had another idea I forgot to add in my code:
To save the level, I use the command PlayerPrefs.SetString for each created element (Wall, floor…)
I’m nor sure but it seems that PlayerPrefs is very slow on WebGL; do you have info about this?

Yeah repeated calls to PlayerPrefs is probably a huge bottleneck. That’s my gut feel, I’ve never timed it. If you want to save the data, just store the elements into one big string and call SetString once when you’re done. For example, off the top of my head (note that GetPixels32 orders the rows bottom-to-top, so mapData will reflect this, and it’s the reason “y” is calculated as shown):

public Texture2D map;  // pretend we set this in the Inspector

public void InitMapData()
{
    Color32[] px = map.GetPixels32();
    string mapData = new string(' ', px.length); // initialize to a bunch of spaces
    for(int i = 0; i < px.length; i++)
    {
        int x = (i % mapData.height);
        int y = mapData.height - (i / mapData.height);

        if(px[i] == Color.red)
        {
            mapData[i] = '1'; // wall
            // todo - create and position wall
        }

        if(px[i] == Color.blue)
        {
            mapData[i] = '0'; // floor
            // todo - create and position floor
        }
    }

    PlayerPrefs.SetString("map_data", mapData);
    PlayerPrefs.Save();
}

I will try your method to compare the perfs !
You’re right, it would be better to read the pixels once instead of read it for each cases.
thanks

After some test on my Website, I found that the problème was not the GetPixel (less than 1s to create the level) but the Save fonction…
I tried to put it in a single string but with 200000 characters, the string was a little too big…
But with a serialized object, it was much better and now, I have no performance issues anymore.
thanks