Юнити как изменить цвет объекта через код

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

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

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.

using System.Collections; using System.Collections.Generic; using UnityEngine; public class Ball : MonoBehaviour { private Renderer mr; void Start() { // We want the renderer component of this object // so we call GetComponent<Renderer>() to get it. // In this case, it will return the Mesh Renderer // of this sphere object. mr = GetComponent<Renderer>(); // Set a new color to the material of the object. mr.material.color = new Color(1f, 0f, 1f, 1f); } }

Code language: C# (cs)

Let me explain it in more detail.

mr = GetComponent<Renderer>();

Code language: C# (cs)

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.

mr.material.color = new Color(1f, 0f, 1f, 1f);

Code language: C# (cs)

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.

new Color(red, green, blue, alpha);

Code language: C# (cs)

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

struct in
UnityEngine

/

Implemented in:UnityEngine.CoreModule

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Your name

Your email

Suggestion*

Cancel

Description

Representation of RGBA colors.

This structure is used throughout Unity to pass colors around.
Each color component is a floating point value with a range from 0 to 1.

Components (r,g,b) define a color in RGB color space. Alpha component (a)
defines transparency — alpha of one is completely opaque, alpha of zero is completely
transparent.

Static Properties

black Solid black. RGBA is (0, 0, 0, 1).
blue Solid blue. RGBA is (0, 0, 1, 1).
clear Completely transparent. RGBA is (0, 0, 0, 0).
cyan Cyan. RGBA is (0, 1, 1, 1).
gray Gray. RGBA is (0.5, 0.5, 0.5, 1).
green Solid green. RGBA is (0, 1, 0, 1).
grey English spelling for gray. RGBA is the same (0.5, 0.5, 0.5, 1).
magenta Magenta. RGBA is (1, 0, 1, 1).
red Solid red. RGBA is (1, 0, 0, 1).
white Solid white. RGBA is (1, 1, 1, 1).
yellow Yellow. RGBA is (1, 0.92, 0.016, 1), but the color is nice to look at!

Properties

a Alpha component of the color (0 is transparent, 1 is opaque).
b Blue component of the color.
g Green component of the color.
gamma A version of the color that has had the gamma curve applied.
grayscale The grayscale value of the color. (Read Only)
linear A linear value of an sRGB color.
maxColorComponent Returns the maximum color component value: Max(r,g,b).
r Red component of the color.
this[int] Access the r, g, b,a components using [0], [1], [2], [3] respectively.

Constructors

Color Constructs a new Color with given r,g,b,a components.

Public Methods

ToString Returns a formatted string of this color.

Static Methods

HSVToRGB Creates an RGB colour from HSV input.
Lerp Linearly interpolates between colors a and b by t.
LerpUnclamped Linearly interpolates between colors a and b by t.
RGBToHSV Calculates the hue, saturation and value of an RGB input color.

Operators

Color Colors can be implicitly converted to and from Vector4.
operator — Subtracts color b from color a. Each component is subtracted separately.
operator * Multiplies two colors together. Each component is multiplied separately.
operator / Divides color a by the float b. Each color component is scaled separately.
operator + Adds two colors together. Each component is added separately.
Vector4 Colors can be implicitly converted to and from Vector4.

In this post, we will learn how to change/update the color of an image, text, and other 2D UI elements. Before going in-depth let’s have a brief on Unity’s Color. In Unity 3D the Color.color having the combination of RGB with an Alpha value which is responsible for the transparency of the color.

To create a color you need four input values like
r – Red color value
g – Green color value
b – Blue color value
a – Alpha value,
these values are range between 0 – 255 on the Unity’s color picker window.

Unity Color Picker Window
Unity Color Picker Window
RGB vs Hexadecimal Color

RGB is a color scope of light using Red, Green, and Blue to render the colors onscreen. RGB is the primary color that provides different colors when mixed. Hexadecimal color code is similar to the RGB combination but it mentioned with the hex value of RGB input. The first two digits represent the Red color, the third and fourth digits for Green color, the last two digits represent Blue color. In most programming tools the color input will be in hexadecimal value, also it is easy to handle the color combination.

Create Color in C#

To create a new color variable do the following

When using color code in C# the input value range from 0 – 1, the method can be used without alpha value also.

The above two example are using the RGB values, we can also use the Hexadecimal color code as following.

Parse Hexadecimal Color Code

To create color from the hexadecimal value we need to use a inbuilt method to handle.

ColorUtility.TryParseHtmlString helps to parse the hex color code to the color variable.

Create Color Variable in Unity Editor

To create a color variable from the Inspector you need to create a public variable for color.

Add pick your desire color from the color picker window.

Create Color From Editor

Create Color From Editor
Changing Color of UI Elements

To change the color of image, button, text and other UI elements first access the game object and update the color with new one.

Hope this post will helpful to you, Happy Coding!.

Join the Discord. Talk about Game Dev. Talk about Gaming.

If you’ve ever wanted to write a script that could make your sprite flash a different colour or turn them transparent in Unity, there’s an easy way. I did this in various ways in my game Puzzledorf. One example is the fireworks that explode when you do something right:

Or making the Press Any Key text fade in and out on the Titlescreen, or the fading button highlights on the menus:

Sprite Renderer

You’re sprite is contained in a component called the Sprite Renderer.

Sprite Renderer

Now if you click on “Color”, you can manually change the sprites transparency in the colour changer by turning alpha down to 0, or tint the sprite by modifying how much red, blue and green is in the image.

Color Changer

Confusingly, if it’s set to all white, the sprite is its normal colour, while all black will make the sprite black. You’ll notice also that the colours range from 0 to 255, with 0 being no colour and 255 being full colour.

Now unfortunately if you turn blue and green off, the sprite won’t be all red, just tinted red. If you want to completely change colours, you’ll have to start with a white sprite, otherwise it will just tint.

Coding Colour Changes

To change the colour in a script, you will need to get the Sprite Renderer in your code, and then we can easily change it’s color property. (Color is the American spelling whereas colour is the Australian spelling).

Create a scene with a game object that has a sprite renderer / sprite attached. Then create a new script called ColourChange and add the following code:

    SpriteRenderer sprite;
   
    void Start()
    {
        sprite = GetComponent<SpriteRenderer>();
    }
    
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.C))
        {            
            // Change the 'color' property of the 'Sprite Renderer'
            sprite.color = new Color (1, 0, 0, 1); 
        }
    }

The very first thing we do is create a variable to store the Sprite Renderer, and we call this sprite. Then in Start() we get the component for the Sprite Renderer, so this way we can access it’s color property. If your sprite is in a child game object of where you attached this script, instead of GetComponent, use GetComponentInChildren like this:

sprite = GetComponentInChildren<SpriteRenderer>();

Now in Update() we first of all check to see if the key C is being pressed on the keyboard. If you’re confused with how that works, read the Unity documentation on it here; it’s helpful.

Then we change the color property of our Sprite Renderer by creating a new Color. This literally just means we’re changing those same colour properties from earlier, but with code. It looks like this:

sprite.color = new Color (Red, Green, Blue, Alpha);

Confusingly, instead of being a value between 0 and 255, like it was in the editors colour changer, now we have to give it a value between 0 and 1 for each colour property, 0 being no colour, 1 being full colour for that property.

So in other words, if you run your game and test it now, it will tint your sprite red, because we told it to be:

  • Full Red
  • No Green
  • No Blue
  • Fully Visible

Likewise if we changed our colour property like this:

sprite.color = new Color (0, 1, 0, 1);

It would tint our sprite green. Try it.

Then if you did this:

sprite.color = new Color (1, 1, 1, 0);

Your sprite would be its normal colour, but it would be transparent, because we turned the alpha all of the way down. So that’s a nice way to make your sprite invisible, but still enabled.

You should be able to use this to create some nice effects in your games now like a character flashing when it’s hurt.

Понравилась статья? Поделить с друзьями:
  • Юнити как изменить разрешение экрана
  • Юнити как изменить размер камеры
  • Юнит мультиварка ошибка е4
  • Юнистрим код ошибки 4
  • Юник 370 ошибка е11