Search code examples
c#unity-game-enginegame-developmentgameobject

Change Color of a public GameObject in script [Unity]


I created a gameobject call archor, it has a script attached to it, that script refers to a gameobject (e.g. Wall) through

public GameObject Wall (in code)

Then I drag a prefab from Unity Editor into that slot

Now, inside the script, I would like to change Wall 's color through code

I have tried

Wall.SpriteRenderer.color = Color.Red;
Wall.material.color = Color.Red;
Wall.material.SetColor 
or even 
Wall.SpriteRenderer.SetColor 

and none of them worked

Do I have to name the Renderer of Gameobject before I can refer to it ?

So if I have Wall , TallWall, ShortWall and I want to change their color, will I have to name each Renderer first?

What is the different between Setcolor and .color?

All this code is put in void Start()

Thanks in advance quite confusing

I expect some simple explanation


Solution

  • You always should select right type of an object to use. You should change the variables type to the SpriteRenderer if it is a SpriteRenderer and you want to change it color. If it is a 3D model use Renderer instead.

    SetColor allow you to set different color parameters in material, color will set just one of them.

    So ith you are useing the sprite rendere your code could llok like this :

        public class WallColorChanger : MonoBehaviour
        {
            [SerializeField] private SpriteRenderer wall;
            [SerializeField] private SpriteRenderer wallTall;
            [SerializeField] private SpriteRenderer wallShort;
    
            private void Start()
            {
                SetColor(wall, Color.white);
                SetColor(wallShort, Color.red);
                SetColor(wallTall, Color.white);
            }
    
            private void SetColor(SpriteRenderer sprite, Color color)
            {
                sprite.color = color;
            }
        }
    

    If you case of them being a 3D objects you will need to change SetColor to work with Renderer and adjust the material value.