简体   繁体   中英

Instantiate prefabs according to a 2d list and replace afterwards

I'm new to unity programming and trying to recreate a puzzle game I once created in Java. To generate the "playing field" I have a 2d list which contains 0's, 1's and 2's. Now I want to create a visual matrix which corresponds with the 2d list.

I first instantiate a prefab in the visual matrix when the 2d list equals a 1 or a 2 on a specific position, creating a square. But now my question is how can I change the instantiated prefabs? The game requires me to change a value in the 2d list from 1 to 0 or vice versa, which also means the visual representation should change.

So my question is, what is the best way to do this or how can I change an already created prefab if needed? (Is there a way to name them or reference them or something?)

Let's say this is how you instantiate your object

GameObject[,] objects = new GameObject[LENGTH, WIDTH];
for(int i = 0; i < LENGTH; i++){
    for(int j = 0; j < WIDTH; j++){
        objects[i, j] = (GameObject)Instantiate(Prefab);
        //Set position and do other initialization stuff here
    }
}

There's a couple ways you can make it change based on changes made to the matrix.

1) Whenever you make a change to the matrix, just directly change the sprite of the object:

matrix[1,2] = 1;
objects[1,2].getComponent<SpriteRenderer>().sprite = sprite1;

matrix[2,3] = 0;
objects[2,3].getComponent<SpriteRenderer>().sprite = sprite0;

In this sprite1 and sprite0 would probably be set through the inspector by declaring them as public variables in code.

2) Make an update function that will change the visual representation of the GameObject array based on the integer array

void update(){
    for(int i = 0; i < LENGTH; i++){
        for(int j = 0; j < LENGTH; j++){
            switch(matrix[i, j]){
                case 0:
                    objects[i, j].getComponent<SpriteRenderer>().sprite = sprite0;
                    break;
                case 1:
                    objects[i, j].getComponent<SpriteRenderer>().sprite = sprite1;
                    break;
                case 2:
                    objects[i, j].getComponent<SpriteRenderer>().sprite = sprite2;
                    break;
            }
        }
    }
}

With this update function, whenever you want to update the visual representation of the matrix you just run it. Keep in mind, the way I've written the code depends on the matrix array and the objects array being public. You could get around this by taking both of them as parameters.

Also, as mentioned before, you would probably set sprite0, sprite1, and sprite2 through the inspector by declaring them as public variables in code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM