Search code examples
c#arraysunity-game-engineinstantiation

Spawn multiple cubes with Array data


I want help with this problem of mine. Let's consider I want to spawn a Rubik cube (3 3 3). And I want the spawning to happen in this way where we pass 4 data to the game / every cube has 4 data like x,y,z,t where x,y,z are location coordinates & t is the type of the cube. For example let's say (0,0,0,r). I need a red cube to spawn where r is red to spawn at 0,0,0 in unity. Another example is (0,2,0,b) where I need a blue cube to spawn at 2 in y. Hope you guys get the idea. So, with data like this i want to spawn a 333 cube.

Why I want this kind of array is in the future if I want to spawn a 10 * 10 * 10 cube. I need such data so I can only spawn the outer layer of the cube and not the ones inside. To save performance issues.


Solution

  • This sounds pretty straight forward:

    public enum CubeType
    {
        white,
        yellow,
        blue,
        red,
        green,
        orange
    }
    
    private readonly IReadOnlyDictionary<CubeType, Color> colors = new Dictionary<CubeType, Color>
    {
        {CubeType.white, Color.white},
        {CubeType.yellow, Color.yellow},
        {CubeType.blue, Color.blue},
        {CubeType.red, Color.red},
        {CubeType.green, Color.green},
        {CubeType.orange, Color.orange},
    }
    
    // Size/Expands of one cube tile
    public float cubeSize = 1f;
    public GameObject prefab;
    // Amount of layers/dimensions e.g. 3x3
    public int dimensions = 3;
    
    public void SpawnCube(int x, int y, int z, CubeType type)
    {
        var cube = Instantiate (prefab, new (Vector3(x,y,z) - Vector3.one * dimensions / 2f) * cubeSize, Quaternion.identity);
        // Or whatever you want to do with the type
        cube.GetComponent<Renderer>().material.color = colors[type];
    }