How to change colors for any object in unity?
I want to change color for every instantiate in C# in unity for every object that created I don’t want that the previous object that created with the same prefab also change his color only for created Please help
2 Answers 2
Suppose you instantiate a GameObject, you can assign (change) the color by simply accessing render and material:
There are a lot of example about this topic.
But I am assuming you want to instantiate objects with different(random) colors.
2 Simple Ways To Change Color Of A 3D Object In Unity
Colors can set the tone of scenes in your game. Using the right colors for the right atmosphere is important. When it comes to changing the color of an object, Unity has made it quite simple to do so, manually and programmatically.
Changing the color of a 3D object can simply be done by setting the Albedo (RGB value) of a material set in the Mesh Renderer component of the 3D object. A new Material must be created and set to the Mesh Renderer component to do this as you are not allowed to edit the default material. Changing color can also be done programmatically by setting the color value of the target material.
You can even change the color of a 3D object that has a texture applied to it. Let me get into the details on how to properly do this, both via the inspector in Unity Editor and via setting the color value programmatically through a script.
Table of Contents
- How To Change The Color Of A 3D Object In Unity
- How To Change The Color Of A 3D Object Programmatically In Unity
How To Change The Color Of A 3D Object In Unity
1. Create a 3D object
First of all, let’s create a simple 3D object, a cube. You can do this by right-clicking on the hierarchy window in the editor and selecting 3D Object > Cube.

Right-click > 3D Object > Cube
This can also be done by clicking on the plus sign on the top-left corner of the hierarchy window and selecting 3D Object > Cube.
Let’s scale it up a bit so it’s easier to see. I set its scale on X-axis and Z-axis to 100 for this but you can set it to whatever you want as long as it’s easy to see.

Enlarge the cube so it’s easier to see
2. Create a Material
Here you’ll see that the new cube we’ve created comes with a renderer component called Mesh Renderer, and it comes with a default material.

Mesh Renderer with a default material
This default material cannot be edited. You need to create a new Material and use that instead.
To create a new Material, right-click on the project window and select Create > Material.

Right-click > Create > Material
Alternatively, you can create a Material by clicking on the plus icon at the top-left corner of the project window and selecting Material.
3. Attach the material to the object’s Mesh Renderer component
Now, we attach the newly created Material to the object’s Mesh Renderer component by dragging and dropping it over the default material in the inspector window.

Drag and drop into the material box
Once attached, it should look something like this:

4. Change the color
Click on the Material file in the project window to inspect its properties. You should be able to see something similar to this in the inspector window:

Material’s properties
Click on the color picker (the white rectangle you see in the image above) next to the word “Albedo” and pick whatever color you want. You can also set how metallic and how smooth the object looks.

Color Picker
Adjust it until you get your desired result. Changes can be seen in real-time.

This also works on a textured 3D object. Take a look at this brick wall textured object:

A textured object
When a color is applied to a textured object, the selected color will be applied on top of the texture.

A textured object with color applied to it.
And that’s it! Easy, right? Now, let’s take a look at how to do it via a script.
How To Change The Color Of A 3D Object Programmatically In Unity
It is possible to change the color of a 3D object programmatically. You can do so by setting the color value of the material attached to the object.
1. Create a 3D object
Here, let’s create a sphere. Right-click on the hierarchy window and select 3D Object > Sphere and you’ll get a nice and round 3D game object. Name it whatever you want.

A sphere
2. Create a new script file and attach it to the object
Now we need to give the newly created object a script for it to run. Right-click on the project window and select Create > C# Script.

Right-click > Create > C# Script
Alternatively, you can click on the plus icon at the top-left corner of the project window and select C# Script to create a script file.
Attach the script by dragging and dropping it onto the object in the hierarchy window. Confirm that the script is properly attached by looking in the inspector window of the object. If you can see the script there, you’re good to go.

The script is attached
Once you’ve confirmed that the script has been properly attached, double-click on the script file to open it and start coding.
3. Write the script
Let’s start coding! The color can be changed by setting the color value of the renderer’s material.
We’ll put the code inside the Start function so we can see the result as soon as the object finishes loading.
Let me explain it in more detail.
This gets the Renderer component of the object that this script is attached to. In our case, the Mesh Renderer component will be returned and stored in a variable.
This line sets the color of the material to pink. The Color class takes 4 parameters: Red, green, blue, and alpha (transparency), respectively. Each parameter can have a value from 0 to 1.
Save the script file and go back to Unity Editor and run the game. You should be able to see the color changes as soon as the game starts.

The sphere changed color
Note that you don’t have to create a Material file and attach it to the renderer to change the color of an object via a script, but I recommend you to do it as it will give you more control.
And that is all! Let me know in the comment section below what you think, or if I miss anything.
Thank you for reading and happy coding!
Attribution
- Brick Wall texture by designer_thinks on Freepik
- Paint Bucket icon made by Smashicons from www.flaticon.com
Hi, I'm Pavee. I'm a software developer, an aspiring pixel artist, and the owner of Game Dev Planet. I love learning new things and have a passion for game development.
6 — Раскрашиваем мир, материалы в Unity
— узнаём о том, что разные объекты могут иметь один и тот же материал. И если его отредактировать, автоматически изменится внешний вид всех объектов с этим материалом.
— знакомимся с понятием текстура – texture
— добавляем на сцену новый 3D-объект Plane, который в играх часто используется в качестве плоскости пола.
— создаём новый материал с именем grass (трава), чтобы нанести его на Plane
— учимся позиционировать (размещать) объекты на сцене так, чтобы они хорошо был видны в окне Game при запуске игры или предварительном просмотре. Для этого регулируем положение (координаты и наклон) как самих объектов, так и камеры (Main Camera)
— узнаём о том, что лучше начинать создавать игровую локацию в начале координат (центре) сцены — ЭТО ВАЖНО!
— для быстрого обнуления координат объекта Plane используем инструмент Reset Position контекстного меню компонента Transform в окне Inspector. Аналогично можно обнулять координаты любого объекта
— знакомимся с возможностью переключения вида сцены на вид сверху для более удобного и быстрого перемещения объектов и сбоку для переориентации на сцене
— находим в интернете текстуру травы и используем её для соответствующего материала,
— настраиваем tiling (частоту повторяемости) текстуры в материале для большей реалистичности отображения.
Цикл уроков создан при поддержке компании Melsoft games.
Creating and Using Materials
To create a new Material, use Assets->Create->Material from the main menu or the Project View context menu.
By default, new materials are assigned the Standard Shader, with all map properties empty, like this:

Используйте пункт главного меню Assets->Create->Material или контекстное меню окна Project (Project View) для создания нового материала. После создания, вы можете применить его к объекту и настроить все его свойства в инспекторе (Inspector). Для применения материала к объекту, просто перетащите его из окна Project (Project View) на любой объект в сцене (Scene) или иерархии сцены (Hierarchy).
Установка свойств материала
Вы можете выбрать какой именно шейдер будет использоваться в конкретном материале. Для этого просто раскройте выпадающее меню Shader в инспекторе и выберите подходящий вам шейдер. Выбранный вами шейдер будет задавать доступные для изменения свойства. Свойствами могут выглядеть как цвета, слайдеры, текстуры, числа или векторы. Если вы применили материал к активному объекту в сцене, вы увидите, как в реальном времени будут применяться изменяемые вами свойства.
Существует два способа присваивания текстуры (Texture) свойству.
- С помощью перетаскивания текстуры из окна Project на квадратную область свойства Texture
- С помощью нажатия кнопки Select и выбора текстуры из появившегося выпадающего списка
В дополнение к основным шейдерам, применяемым к игровым объектам, существует ряд других категорий для особых целей:-
- FX: водные и световые эффекты.
- GUI: отображение графического интерфейса пользователя (GUI — это аббревиатура для Graphic User Interface, что в переводе означает “графический интерфейс пользователя”).
- Mobile: Simplified high-performance shader for mobile devices.
- Nature: деревья и земная поверхность.
- Particles: эффекты системы частиц.
- Skybox: For rendering background environments behind all geometry
- Sprites: For use with the 2D sprite system
- Unlit: For rendering that entirely bypasses all light & shadowing
- Legacy: The large collection of older shaders which were superseded by the Standard Shader
Технические детали шейдера
A Shader is a script which contains mathematical calculations and algorithms for how the pixels on the surface of a model should look. The standard shader performs complex and realistic lighting calculations. Other shaders may use simpler or different calculations to show different results. Within any given Shader are a number of properties which can be given values by a Material using that shader. These properties can be numbers, colours definitions or textures, which appear in the inspector when viewing a Material. Materials are then used by Renderer components attached to Game Objects, to render each Game Object’s mesh.
It is possible and often desirable to have several different Materials which may reference the same textures. These materials may also use the same or different shaders, depending on the requirements.
Below is an example of a possible set-up combination using three materials, two shaders and one texture.

In the diagram we have a red car and a blue car. Both models use a separate material for the bodywork, “Red car material” and “Blue car material” respectively.
Both these bodywork materials use the same custom shader, “Carbody Shader”. A custom shader may be used because the shader adds extra features specifically for the cars, such as metallic sparkly rendering, or perhaps has a custom damage masking feature.
Each car body material has a reference to the “Car Texture”, which is a texture map containing all the details of the bodywork, without a specific paint colour.
The Carbody shader also accepts a tint colour, which is set to a different colour for the red and blue cars, giving each car a different look while using a single texture for both of them.
The car wheel models use a separate material again, but this time both cars share the same material for their wheels, as the wheels do not differ on each car. The wheel material uses the Standard Shader, and has a reference again to the Car Texture.
Notice how the car texture contains details for the bodywork and wheels — this is a texture atlas, meaning different parts of the texture image are explicitly mapped to different parts of the model.
Even though the bodywork materials are using a texture that also contains the wheel image, the wheel does not appear on the body because that part of the texture is not mapped to the bodywork geometry.
Similarly, the wheel material is using the same texture, which has bodywork detail in it. The bodywork detail does not appear on the wheel, because only the portion of the texture showing the wheel detail is mapped to the wheel geometry.
This mapping is done by the 3D artist in an external 3d application, and is called “UV mapping”.
Если быть точнее, шейдер определяет:
- The method to render an object. This includes code and mathematical calculations that may include the angles of light sources, the viewing angle, and any other relevant calculations. Shaders can also specify different methods depending on the graphics hardware of the end user.
- The parameters that can be customised in the material inspector, such as texture maps, colours and numeric values.
- Какие текстуры использовать для отрисовки.
- The specific values for the shader’s parameters — such as which texture maps, the colour and numeric values to use.
Написанием шейдеров должны заниматься программисты 3D графики. Шейдеры создаются при помощи довольно простого языка ShaderLab. Однако, заставить шейдер правильно работать на множестве различных видеокарт — непростая задача и она требует хороших всесторонних знаний о том, как работают графические адаптеры.
A number of shaders are built into Unity directly, and some more come in the Standard Assets Library.