Unity как изменить прозрачность объекта

Create transparent material in unity editor and at run time. Change material transparency in unity editor and at runtime.

In this tutorial, we will see how to use transparent materials in unity 3D.

In this post, we will cover following points.

  • create transparent materials in unity Editor
  • change material transparency in unity editor
  • create transparent material at runtime
  • change material transparency at runtime

Create Transparent material in Unity Editor

Step 1: Create material with editor menu: Asset -> Create -> Materials

Step 2: Select material and change it’s Rendering Mode property to Transparent.

Change rendering mode to Transparent

Change material transparency in editor

To change the transparency, we have to change Alpha (a) value of material color. We can do this with color picker in the editor. We can change this value to modify transparency of the material.

If alpha value of color is 0 then the material is completely transparent and if it is 1.0 then it will look like opaque material. If the you need 50% transparency then make it 0.5.

Change material transparency unity editor

Create transparent material in unity at runtime

First we will create a material. By, default it will be opaque. Then we will change it to transparent material.

// create a new material

Material mat = new Material(Shader.Find(«Standard»));

Change material to Transparent

Use below code to convert a material to transparent.

// set rendering mode to transparent

mat.SetFloat(«_Mode», 3);

mat.SetInt(«_SrcBlend», (int)UnityEngine.Rendering.BlendMode.One);

mat.SetInt(«_DstBlend», (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);

mat.SetInt(«_ZWrite», 0);

mat.DisableKeyword(«_ALPHATEST_ON»);

mat.DisableKeyword(«_ALPHABLEND_ON»);

mat.EnableKeyword(«_ALPHAPREMULTIPLY_ON»);

mat.renderQueue = 3000;

Note: The above code might not work in the packaged build of the project, because unity does not include any shader variants which is not included in the scene. To fix this, add a game object in the scene which uses transparent material. You can disable this game object, but it will allow to include required shader variants in the build.

Change material transparency at runtime

Change alpha value of the color to change transparency.

MeshRenderer mr = GetComponent<MeshRenderer>();

Color col = mr.material.color;

col.a = value; // pass float value here

mr.material.color = col;

Download demo project unity package – Material_Demo_Transparent.zip

To know more about material handling at runtime, checkout my post Change Material at Runtime.

That’s all for this tutorial. Please post your comments for queries and feedback. Thanks for reading.

Share Button

The following two tabs change content below.

  • Bio
  • Latest Posts

Gyanendu Shekhar is a technology enthusiast. He loves to learn new technologies. His area of interest includes Microsoft technologies, Augmented reality, Virtual reality, unity3d and android development.

Gyanendu Shekhar

Gyanendu Shekhar is a technology enthusiast. He loves to learn new technologies. His area of interest includes Microsoft technologies, Augmented reality, Virtual reality, unity3d and android development.

Прозрачность объекта

Прозрачность объекта

Здравствуйте. Нужно менять прозрачность у объекта. Без создания шейдера. И код желательно на JS. Заранее спасибо

avtar1870
UNIт
 
Сообщения: 74
Зарегистрирован: 17 мар 2016, 14:53

Re: Прозрачность объекта

Сообщение MANMANA 17 мар 2016, 16:11

gameObject.GetComponent<Renderer> ().material.color.a = 0;
шейдер должен поддерживать прозрачность

MANMANA
UNIверсал
 
Сообщения: 475
Зарегистрирован: 31 июл 2014, 10:32
Откуда: Moscow
  • Сайт

Re: Прозрачность объекта

Сообщение avtar1870 17 мар 2016, 16:54

Изображение

MANMANA писал(а):gameObject.GetComponent<Renderer> ().material.color.a = 0;
шейдер должен поддерживать прозрачность

avtar1870
UNIт
 
Сообщения: 74
Зарегистрирован: 17 мар 2016, 14:53

Re: Прозрачность объекта

Сообщение DualPain 17 мар 2016, 17:18

у класса GameObject нет метода GetComponent, обращайтесь к экземпляру класса

DualPain
Старожил
 
Сообщения: 727
Зарегистрирован: 11 янв 2013, 01:18
Skype: demon21.09

Re: Прозрачность объекта

Сообщение avtar1870 17 мар 2016, 17:33

DualPain писал(а):у класса GameObject нет метода GetComponent, обращайтесь к экземпляру класса

А не подскажете как?

avtar1870
UNIт
 
Сообщения: 74
Зарегистрирован: 17 мар 2016, 14:53

Re: Прозрачность объекта

Сообщение DualPain 17 мар 2016, 17:53

так как написали в этом комментарии или у вас выше через трансформ или по-моему вообще можно просто вызывать GetComponent

MANMANA писал(а):gameObject.GetComponent<Renderer> ().material.color.a = 0;
шейдер должен поддерживать прозрачность

DualPain
Старожил
 
Сообщения: 727
Зарегистрирован: 11 янв 2013, 01:18
Skype: demon21.09

Re: Прозрачность объекта

Сообщение avtar1870 17 мар 2016, 18:14

DualPain писал(а):так как написали в этом комментарии или у вас выше через трансформ или по-моему вообще можно просто вызывать GetComponent

MANMANA писал(а):gameObject.GetComponent<Renderer> ().material.color.a = 0;
шейдер должен поддерживать прозрачность

Я написал как в этом комментарии и ошибка, которую я выше скрином разместил

avtar1870
UNIт
 
Сообщения: 74
Зарегистрирован: 17 мар 2016, 14:53

Re: Прозрачность объекта

Сообщение immeasurability 17 мар 2016, 18:37

gameObject!=GameObject

Discord era#6140

youtube.com/user/immeasurability/videos

Аватара пользователя
immeasurability
Адепт
 
Сообщения: 1097
Зарегистрирован: 08 авг 2013, 18:09

Re: Прозрачность объекта

Сообщение avtar1870 17 мар 2016, 18:47

immeasurability писал(а):gameObject!=GameObject

К сожалению, не помогло.
Изображение

avtar1870
UNIт
 
Сообщения: 74
Зарегистрирован: 17 мар 2016, 14:53

Re: Прозрачность объекта

Сообщение DualPain 17 мар 2016, 19:03

нельзя напрямую изменять альфу цвета
напишите так

Используется csharp

Material mat = GetComponent<Renderer>().material;
Color color = mat.color;
color.a = 0;
mat.color = color;
 

DualPain
Старожил
 
Сообщения: 727
Зарегистрирован: 11 янв 2013, 01:18
Skype: demon21.09

Re: Прозрачность объекта

Сообщение avtar1870 17 мар 2016, 19:36

DualPain писал(а):нельзя напрямую изменять альфу цвета
напишите так

Используется csharp

Material mat = GetComponent<Renderer>().material;
Color color = mat.color;
color.a = 0;
mat.color = color;
 

А можно код на JS?

avtar1870
UNIт
 
Сообщения: 74
Зарегистрирован: 17 мар 2016, 14:53

Re: Прозрачность объекта

Сообщение DualPain 17 мар 2016, 19:46

а в чем проблема? вы не знаете как объявить переменные на js?

DualPain
Старожил
 
Сообщения: 727
Зарегистрирован: 11 янв 2013, 01:18
Skype: demon21.09

Re: Прозрачность объекта

Сообщение avtar1870 17 мар 2016, 20:01

DualPain писал(а):а в чем проблема? вы не знаете как объявить переменные на js?

Ругается не первую строчку. Что-то со скобками и точкой с зяпятой не нравиться

Используется javascript

private var mat : Material  = GetComponent<Renderer>().material;

avtar1870
UNIт
 
Сообщения: 74
Зарегистрирован: 17 мар 2016, 14:53

Re: Прозрачность объекта

Сообщение DualPain 17 мар 2016, 20:46

DualPain
Старожил
 
Сообщения: 727
Зарегистрирован: 11 янв 2013, 01:18
Skype: demon21.09

Re: Прозрачность объекта

Сообщение avtar1870 17 мар 2016, 21:02

Переменную я вроде правильно создал.

avtar1870
UNIт
 
Сообщения: 74
Зарегистрирован: 17 мар 2016, 14:53


Вернуться в Почемучка

Кто сейчас на конференции

Сейчас этот форум просматривают: Yandex [Bot] и гости: 17



Specular mode: Specular parameter

A Standard Shader material with default parameters and no values or textures assigned. The Albedo Color parameter is highlighted.

A Standard Shader material with default parameters and no values or textures assigned. The Albedo Color parameter is highlighted.

The Albedo parameter controls the base color of the surface.

A range of black to white albedo values

A range of black to white albedo values

Specifying a single color for the Albedo value is sometimes useful, but it is far more common to assign a texture map for the Albedo parameter. This should represent the colors of the surface of the object. It’s important to note that the Albedo texture should not contain any lighting, since the lighting will be added to it based on the context in which the object is seen.

Two examples of typical Albedo texture maps. On the left is a texture map for a character model, and on the right is a wooden crate. Notice there are no shadows or lighting highlights.

Two examples of typical Albedo texture maps. On the left is a texture map for a character model, and on the right is a wooden crate. Notice there are no shadows or lighting highlights.

Transparency

The alpha value of the Albedo colour controls the transparency level for the material. This only has an effect if the Rendering Mode for the material is set to one of the transparent mode, and not Opaque. As mentioned above, picking the correct transparency mode is important because it determines whether or not you will still see reflections and specular highlights at full value, or whether they will be faded out according to the transparency values too.

A range of transparency values from 0 to 1, using the Transparent mode suitable for realistic transparent objects

A range of transparency values from 0 to 1, using the Transparent mode suitable for realistic transparent objects

When using a texture assigned for the Albedo parameter, you can control the transparency of the material by ensuring your albedo texture image has an alpha channel. The alpha channel values are mapped to the transparency levels with white being fully opaque, and black being fully transparent. This will have the effect that your material can have areas of varying transparency.

An imported texture with RGB channels and an Alpha Channel. You can click the RGB/A button as shown to toggle which channels of the image you are previewing.

An imported texture with RGB channels and an Alpha Channel. You can click the RGB/A button as shown to toggle which channels of the image you are previewing.
The end result, peering through a broken window into a building. The gaps in the glass are totally transparent, while the glass shards are partially transparent and the frame is fully opaque.
The end result, peering through a broken window into a building. The gaps in the glass are totally transparent, while the glass shards are partially transparent and the frame is fully opaque.

Specular mode: Specular parameter

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

Параметр Albedo управляет основным цветом поверхности.

Диапазон значений альбедо от черного до белого

Диапазон значений альбедо от черного до белого

Указание одного цвета для значения альбедо иногда полезно, но гораздо чаще для параметра альбедо назначается карта текстуры. Это должно представлять цвета поверхности объекта. Важно отметить, что текстура Albedo не должна содержать никакого освещения, поскольку освещение будет добавлено к ней в зависимости от контекста, в котором виден объект.

Два примера типичных текстурных карт Альбедо. Слева карта текстур для модели персонажа, а справа деревянный ящик. Обратите внимание, что нет теней или световых бликов..

Два примера типичных текстурных карт Альбедо. Слева карта текстур для модели персонажа, а справа деревянный ящик. Обратите внимание, что нет теней или световых бликов.

Прозрачность

Альфа-значение цвета альбедо определяет уровень прозрачности материала. Это действует только в том случае, если ВизуализацияПроцесс рисования графики на экране (или текстуры рендеринга). По умолчанию основная камера в Unity отображает изображение на экране. Подробнее
См. в Словарь
Для материала установлен один из режимов прозрачности, и не Непрозрачный. Как упоминалось выше, выбор правильного режима прозрачности важен, потому что он определяет, будете ли вы по-прежнему видеть отражения и зеркальные блики в полном объеме или они также будут исчезать в соответствии со значениями прозрачности.

Диапазон значений прозрачности от 0 до 1 с использованием прозрачного режима, подходящего для реалистичных прозрачных объектов.

Диапазон значений прозрачности от 0 до 1 с использованием прозрачного режима, подходящего для реалистичных прозрачных объектов.

При использовании текстуры, назначенной для параметра альбедо, вы можете управлять прозрачностью материала, обеспечив наличие у изображения текстуры альбедо альфа-канал. Значения альфа-канала сопоставляются с уровнями прозрачности, при этом белый цвет полностью непрозрачен, а черный — полностью прозрачен. Это приведет к тому, что ваш материал может иметь области различной прозрачности.

Импортированная текстура с каналами RGB и альфа-каналом. Вы можете нажать кнопку RGB/A, как показано, для переключения каналов просматриваемого изображения.

Импортированная текстура с каналами RGB и альфа-каналом. Вы можете нажать кнопку RGB/A, как показано, для переключения каналов просматриваемого изображения.
Конечный результат, заглядывание через разбитое окно в здание. Щели в стекле полностью прозрачны, осколки частично прозрачны, а рама полностью непрозрачна..
Конечный результат, заглядывание через разбитое окно в здание. Щели в стекле полностью прозрачны, осколки частично прозрачны, а рама полностью непрозрачна.

Randen

35 / 35 / 15

Регистрация: 06.01.2014

Сообщений: 707

1

Прозрачность объекта

17.12.2016, 14:13. Показов 44938. Ответов 7

Метки нет (Все метки)


Добрый день.
Делаю прозрачность так

C#
1
2
Color color = new Color(255,255,255,0.5f);
obj.GetComponent<Renderer>().material.color = color;

Пробовал разные шейдеры.
Shader — Transparent/Reflactive делает объект полностью прозрачным.

Как правильно установить полупрозрачность?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



751 / 599 / 203

Регистрация: 06.08.2015

Сообщений: 2,432

17.12.2016, 16:27

2

Transparent/Diffuse ?



1



35 / 35 / 15

Регистрация: 06.01.2014

Сообщений: 707

17.12.2016, 16:35

 [ТС]

3

У меня текстура сама по себе работает только на Alpha Blended



0



294 / 243 / 128

Регистрация: 24.12.2014

Сообщений: 708

17.12.2016, 23:13

4

Цитата
Сообщение от Randen
Посмотреть сообщение

Как правильно установить полупрозрачность?

В свойствах самой текстуры указывали «Alpha Is Transparency»? У меня например без этой опции в новых версиях юнити прозрачность вовсе игнорируется и я обычно указываю текстуру, пусть даже 1 пиксельную в качестве материала, чтобы уже точно сработала прозрачность.



0



751 / 599 / 203

Регистрация: 06.08.2015

Сообщений: 2,432

18.12.2016, 07:49

5

Legasy Shaders/Transparent/Diffuse вполне нормально прозрачность меняет из кода.



1



35 / 35 / 15

Регистрация: 06.01.2014

Сообщений: 707

18.12.2016, 11:17

 [ТС]

6

Cr0c, мне не помогает. Может потому что текстура png. Проблема именно с одним типом объектов. С другими будет работать «Legasy Shaders/Transparent/Diffuse»

Добавлено через 31 секунду
Надо писать свой шейдер)



0



wmysterio

294 / 243 / 128

Регистрация: 24.12.2014

Сообщений: 708

19.12.2016, 17:42

7

Randen, Пробуйте задать шейдер объекту программно(пока обойдёмся без текстур):

C#
1
2
3
4
var renderer = gameObject.GetComponent<Renderer>();
//var renderer = gameObject.GetComponentInChildren<Renderer>(); // если родитель не имеет Renderer, то можно искать первый дочерний объект с этим компонентом
renderer.material.shader = Shader.Find( "Transparent/Diffuse" );
renderer.material.color = Color.white * 0.25f; // белый с 25% не прозрачности

Если объект стал прозрачным, значит что-то не так с текстурой или материалом, который был задан изначально.



0



751 / 599 / 203

Регистрация: 06.08.2015

Сообщений: 2,432

19.12.2016, 22:45

8

Randen, всё работает на пнг. Специально проверил.



1



Tips and Tricks: Unity Transparent Material

Introduction

Oftentimes when creating a game, you will need to create transparent objects. This can be anything from glass windows, walls, ice or maybe just a see-through treasure chest to entice the player to open it. Making an object see through requires using Unity’s transparent materials.

To create a transparent material in Unity you will need to set the render mode to transparent and reduce alpha value, inside the albedo color picker. You can then apply the material to make your objects transparent. In this Tips and Tricks: Unity Transparent Material we are going to walk you through, step by step, and show you how to implement your own transparent materials in Unity.

Getting Started

To begin, we have set up a basic scene in Unity to implement our transparent material. Our scene has a handful of trees that have been placed in front of the camera. These will serve to gauge how well we can see through our object.

Creating Unity’s Transparent Material

To create Unity’s transparent material in Unity we first need to create a materials folder to store our materials. This will help maintain the project’s structure and will ensure that we can locate assets as we build out our projects. This is especially helpful when we are working on large scale projects.

Inside of our materials folder, right click and select Create > Material. This will place a nameless material in our folder. Give the material a name to signify what its purpose is. For this unity tutorial, we will name our material “transparent”.

Select our material and the properties for the transparent material will appear in the inspector. The first thing we need to do is change the rendering mode. The rendering mode defaults to Opaque and this works great for solid colors, but Unity does not render the transparency despite there being an alpha value in the albedo color selector. This is because calculating transparency is a computationally expensive process, and you would not want all of your materials doing that if it was not needed. Set the render mode to Transparent to tell Unity that you want it to be treated transparent.

Next, we will need to lower the alpha value of the Albedo color. Select the white box with the eyedropper tool in the inspector. You will then be greeted with a color picker. The A value is for your alpha which controls transparency. Lower this to something around 60. The lower you go the more transparent the object will become. If you lower it to zero the object will disappear.

Creating a Transparent Object in Unity

Time to create something we can see through. Inside of the scene’s hierarchy, right click and select 3D object > Cube. This will place a cube in our scene. Select the cube and in the inspector increase the X and Y scale to 15. This will turn our cube into a wall. Position your camera so that it is looking at the largest face of the wall.

Apply the Transparent Material to the Object in Unity

It is now time to apply the transparent material. With the Cube selected, expand the Mesh Renderer component in the inspector window. The first property will be Materials. If this is the first material you are applying to the object then you will see an Element 0 field. Click the circle next to default material and type transparent in the search bar to locate the material. You can also drag the material from the project folder into the field or onto the object in the scene view to apply it.

At last, you can see through your cube wall. The only problem is that it does not quite look like glass, water, or any other transparent material.

Creating a Glass Material in Unity

Open up your material in the inspector once again. We can adjust the hue of our material to make it look slightly more like the material we are imitating. Select the Albedo color picker and change the hex value to #63BBCF this will give the material a bluish tint that looks like you are staring through a glass window. Feel free to adjust the color and transparency to your liking.

And now you are ready to create Unity’s transparent materials to apply to walls, windows, 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 Unity Cube Color. Also, leave a comment telling us what you liked or did not 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.

Понравилась статья? Поделить с друзьями:
  • Unity как изменить префаб
  • Unity как изменить позицию объекта через скрипт
  • Unity как изменить ось вращения
  • Unity как изменить направление гравитации
  • Unity как изменить skybox