Как изменить цвет куба в unity

от admin

Tips and Tricks: Unity Cube Color

unity cube color

Many prototypes or first time users will often use Unity’s default cube as a placeholder for their player or other objects in their game world. This cube can look extremely plain and boring to look at. The problem becomes even worse when you add multiple cubes to your scene and can no longer visually track which cube is supposed to be what.

To change a Cube’s color in Unity you will need to create and apply a new material to the cube’s Mesh Renderer materials. This new material can then be changed to the desired color by using the color picker in the material’s inspector. In this Tips and Tricks: Change Cube Color we are going to show you how to do exactly that.

Create a 3D Cube in Unity

To change the color of a Cube we must first have our cube. Create the Cube by right clicking inside the hierarch window and selecting 3D Object > Cube.

Create a Color Material in Unity

Now, create a materials folder to hold your new material. Creating folders is an important part of maintaining project organization. Inside of our new folder, right click and select Create > Material. Give your material a name that represents what the material does. We will name ours “Blue”.

Apply Material to Unity’s Cube

Next, select the cube inside of the Unity’s Hierarchy window. You will notice that the inspector window now lists the components that make up a cube. Expand the Mesh Renderer component. The materials property is where we will apply our material. You can have multiple materials applied to a single GameObject. If you want to add more than one material or color to your object, just increase the size field to the number you require. Drag our Blue material into the Element 0 field to apply it to our cube.

Change Cube Color in Unity’s Inspector

Finally, with our material applied we can now change our Cube’s color. Double click the Blue material inside of the materials folder. This will open the cube’s properties inside of Unity’s inspector window. Under Main Maps you will see a white box with an eye dropper next to it. That is the color picker. Select it to open the color window which contains a color wheel. You can set the color value by picking a color on the color wheel or by setting the RGBA color values. For more on color values and how RGBA affects color, check out our article on Unity’s Color32.

Apply Multiple Materials to Unity Objects

To add a second material or color to our Cube we must first increase the material properties size. Select the cube object and expand out the Mesh Renderer component once again. Inside of the material property set the size value to 2. Now you will see a second element called Element 1.

Now, create a new material the same way we created our Blue material. Name this new material Red. Drag the material into the Element 1 Field. Double click on the Red material to open it inside the inspector. Now once again select the color picker. Now select a red color. Notice how Unity has blended the cube’s two color materials and has created a purplish color. You can also continue to add materials for texture or other aesthetic properties like metallic sheen.

Reusing Materials

Additionally, now that you have created your materials you can reuse them to color multiple cubes or objects inside of Unity. If you wanted to create 1000 blue cubes, you would only ever need the material we created in this tutorial. This ability to reuse components is key to create streamlined games and applications that do not consume your player’s resources. It is important to note that, when you reuse a material and decide to modify it later, the changes will apply to every game object that uses that material.

And now you are ready to change the color of the default Cube and other objects within your own games made in Unity. Thank you for stopping by. Stick around and check out more of our tutorials or posts like our piece on What is a Game Developer’s Salary. Also, leave a comment telling us what you liked or didn’t like about the tutorial. Was it easy to follow along? What do you want to learn next? As always check out some of our published apps below.

4. Материалы и текстуры

По умолчанию все объекты имеют серый цвет. Можно изменить цвет любого объекта с помощью материала.

Материал — это набор свойств объекта, с помощью которых можно изменять внешний вид его поверхности. Материал может содержать в себе: цвет, текстуру, блик, рельеф объекта.

Используй пункт главного меню Assets → Create → Material или контекстное меню окна Проект, для создания нового материала. После создания, ты можешь применить его к объекту и настроить все его свойства в Инспекторе. Для применения материала к объекту, просто перетащи его из окна Проект на любой объект в Сцене или Иерархии. Чтобы изменить материал у всех объектов одного prefab’а, необходимо изменить материал у сохраненного prefab’а в окне Проект. Попробуем сделать материалы для моста. Нам понадобятся два цвета: коричневый и темно-коричневый (для столбов). Создадим два материала для этого.

Выбери один из них и в Инспекторе измени цвет (в самом верху, рядом со словом Albedo). Повтори тоже самое с другим материалом.

Теперь необходимо заменить материалы в prefab’е моста. Разверни prefab в окне Проект, нажав на стрелочку:

Выбери несколько объектов, которые должны быть одного цвета. А теперь посмотри на окно Инспектор и найди там компонент Mesh Renderer . Именно он отвечает за то, какого наш объект будет цвета и как он будет отражать свет. Найди свойство Material и разверни его нажав на стрелочку. Ты увидишь число, которому соответствует количество материалов необходимых для этой 3D модели (Size) и, собственно, сами материалы. В нашем случае один материал — Default-Material. Его и нужно заменить, нажав на соседний кружочек .

Теперь ты можешь добавить материалы к остальным элементам prefab’а. Обрати внимание, что изменяя prefab в окне Проект, ты меняешь сразу все его копии на Сцене. Вот, что получилось у нас:

Материалы не только отвечают за свет, как мы уже говорили, но и за другие свойства, например:

Albed — цвет и текстура.

Metallic — определяет металлическая (значение 1) ли поверхность или нет (значение 0).

Smoothness — определяет насколько поверхность глянцевая (значение 1) или шероховатая (значение 0).

4.2. Текстура

Текстура — это растровое изображение, накладываемое на поверхность трехмерной модели для придания ей цвета, окраски или иллюзии рельефа.

Unity поддерживает все самые популярные форматы изображений: jpeg, png, tiff, tga, psd. Текстура должна быть квадратной и иметь следующие размеры: 32х32, 64х64, 128х128, 256х256, 512х512, 1024х1024, 2048х2048, 4096х4096, 8192х8192. Если не следовать этим правилам — Unity попытается сам преобразовать изображение в нужный размер.

4.3. Импорт текстуры

Создай папку в окне Проект, где будут храниться все текстуры. Предлагаем назвать папку Texture . Нажми на эту папку правой кнопкой мыши и выбери «Import New Asset…». Выбери картинку.

Выбери нужный материал. В окне Инспектор нажми кружочек рядом с параметром Albedo и выбери текстуру.

Для простых объектов (куб, сфера, плоскость) можно изменить количество повторений текстуры на объекте. По умолчанию, текстура не повторяется. Выбери материал, в окне Инспектор параметр Tiling отвечает за повторение текстуры по осям x, y.

4.4. Normal Map

Есть простой сервис http://cpetry.github.io/NormalMap-Online/, где из картинки можно настроить и скачать себе Normal map.

Импорт Normal map

Создай папку в окне Проект, где будут храниться все текстуры. Предлагаем назвать папку Normal map .

Нажми на эту папку правой кнопкой мыши и выбери «Import New Asset…». Выбери картинку.

Выдели в окне проекта, добавленную картинку. В свойстве Texture Type выбери Normal Map .

Чтобы добавить материалу неровность, выбери его, в окне Инспектор нажми кружочек рядом с параметром Normal map и выбери нужную.

4.5. Unity: Создание материала ‘Стекло’

Для создания стекла можно использовать стандартный шейдер и выставить для него Rendering Mode = Transparent и в настройках цвета для Albedo выставить прозрачность (Alpha = 0).

Но можно его сделать более реалистичным. Для этого нужно рядом со стеклом добавить GameObject ▶ Light ▶ Reflection Probe. В ее настройках можно указать уровень детализации побольше Resolution = 512 (будет красиво, но скажется на производительности), а для того, чтобы отображались не только статические объекты, нужно выставить Baking Type в Realtime.

Если для Reflection Probe установить чекбокс в разделе его свойств Runtime Settings ▶ Box Projection , то отражения на стекле будут еще более реалистичными.

По умолчанию для Reflection Probe выставлено значение Refresh Mode = On Awake. Это значит, что динамические объекты (типа персонажа или врагов и т.п.) стекло не будет отражать. Если не жалко ресурсов, но хочется красоты и «реальности», то можно выставить режим обновления на каждый кадр.

Читать:
Disk at once что это

Как изменить цвет куба в unity

Changing a Cube’s Color | Unity Tutorial

What’s a game without color? Color is so crucial in game development. Let’s learn how to change color in Unity. If you are a beginner and want to learn how to build virtual reality games, check out our Unity 3D course!

Suppose we want to change the color of a cube in Unity’s Scene. Unity provides the default material “Default-Material” for the cube. To change the cube’s color, we need to create our own material.

Right-click in the Assets folder in the Project window. Select Create > Material.

As evident in the following image, a material will appear in Assets. Change the material’s name to “CubeMaterial”.

The Inspector will contain attributes of ColorMaterial. Click on the white rectangle in the “Main Maps” section under “CubeMaterial”. This will open a color picker, as you can see in the following image.

Choose a color such as red. The values of the sliders labeled “R”, “G,” “B”, and “A” will change. This is because every color can be represented as a combination of four values: red, green, blue, and alpha. The more red in a color, the higher the red value. The same goes for green and blue.

Alpha refers to a color’s transparency. A purely red color has red and alpha values of 255. Its blue and green values are 0. Give ColorMaterial a purely red color, as has been done in the following screenshot.

To assign Cube this red color, drag and drop ColorMaterial onto the cube in the Scene.

Alternatively, drag and drop ColorMaterial in the Element 0 field in the Cube’s Mesh Renderer component. The cube’s color will become red.

To learn more about Materials in Unity, check out our Unity 3D course, where you build 30 virtual reality games!

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 on the hierarchy window and select 3D Object > Cube to create a cube 3D object.

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.

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.

2 Simple Ways To Change Color Of A 3D Object In Unity

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.

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.

2 Simple Ways To Change Color Of A 3D Object In Unity

Drag and drop into the material box

Once attached, it should look something like this:

Mesh Renderer with a custom Material attached to it.

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 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

Color Picker

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

2 Simple Ways To Change Color Of A 3D Object In Unity

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

A 3D object with a brick wall texture.

A textured object

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

2 Simple Ways To Change Color Of A 3D Object In Unity

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.

2 Simple Ways To Change Color Of A 3D Object In Unity

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 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.

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.

2 Simple Ways To Change Color Of A 3D Object In Unity

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.

Related Posts