Search code examples
c#unity-game-engineinstantiationprefab

How do I change a Unity prefab's sprite after instantiating it based on the data I input?


For context, I don't have much Unity and C# experience, so please don't berate me if the answer is really simple. I'm trying to make a dungeon's edge tiles automatically create walls on their respective edges (e.g. the rightmost column of tiles has walls on its right side). I made a tile prefab that changes its sprite based on 4 booleans, each holding whether or not there is a wall on the side. The prefab works on changing the sprite, so it's not a problem with the prefab itself. I have to instantiate the prefab to change its boolean values, and after adding data into the newly instantiated prefab in the spawner script, the prefab's sprite won't update, and I'm left with the default sprite.

I tried moving the sprite change out of the tile prefab's start() method and into a seperate method to try and get it to update after being instantiated.

void spawnTile(int r, int c) 
    {
        for(int i = 0; i < c; i++)
        {
            for(int j = 0; j < r; j++)
            {
                Instantiate(tile, new Vector3((float)(i * locationIncrement), (float) (-1 * j * locationIncrement), 0), transform.rotation);
                if(i == 0)
                {
                    tile.GetComponent<TileScript>().setLeftWall(true);
                }
                if(i == (c - 1))
                {
                    tile.GetComponent<TileScript>().setRightWall(true);
                }
                if(j == 0)
                {
                    tile.GetComponent<TileScript>().setTopWall(true);
                }
                if(j == (r - 1))
                {
                    tile.GetComponent<TileScript>().setBottomWall(true);
                    
                }  
                tile.GetComponent<TileScript>().updateWalls();
            }
        }
    }

This was the code I used in the spawner method, and even with the aforementioned changes implemented the code still did not work, and left me with all the default sprites instead of the expected updated sprites.


Solution

  • Hi you shouldnt change the prefab, the thing that you need is change the intance that you created.

    var newInstance = Instantiate(tile, new Vector3((float)(i * locationIncrement), (float) (-1 * j * locationIncrement), 0), transform.rotation);
    

    Instantiate is a method that will return the new instance created, you should take that new instance and made the changes to that object.