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 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.
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.
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
The Albedo parameter controls the base color of the surface.
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.
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.
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.
Specular mode: Specular parameter
Параметр Albedo управляет основным цветом поверхности.
Указание одного цвета для значения альбедо иногда полезно, но гораздо чаще для параметра альбедо назначается карта текстуры. Это должно представлять цвета поверхности объекта. Важно отметить, что текстура Albedo не должна содержать никакого освещения, поскольку освещение будет добавлено к ней в зависимости от контекста, в котором виден объект.
Прозрачность
Альфа-значение цвета альбедо определяет уровень прозрачности материала. Это действует только в том случае, если ВизуализацияПроцесс рисования графики на экране (или текстуры рендеринга). По умолчанию основная камера в Unity отображает изображение на экране. Подробнее
См. в Словарь Для материала установлен один из режимов прозрачности, и не Непрозрачный. Как упоминалось выше, выбор правильного режима прозрачности важен, потому что он определяет, будете ли вы по-прежнему видеть отражения и зеркальные блики в полном объеме или они также будут исчезать в соответствии со значениями прозрачности.
При использовании текстуры, назначенной для параметра альбедо, вы можете управлять прозрачностью материала, обеспечив наличие у изображения текстуры альбедо альфа-канал. Значения альфа-канала сопоставляются с уровнями прозрачности, при этом белый цвет полностью непрозрачен, а черный — полностью прозрачен. Это приведет к тому, что ваш материал может иметь области различной прозрачности.
Randen 35 / 35 / 15 Регистрация: 06.01.2014 Сообщений: 707 |
||||
1 |
||||
Прозрачность объекта17.12.2016, 14:13. Показов 44938. Ответов 7 Метки нет (Все метки)
Добрый день.
Пробовал разные шейдеры. Как правильно установить полупрозрачность?
__________________
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 |
Как правильно установить полупрозрачность? В свойствах самой текстуры указывали «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, Пробуйте задать шейдер объекту программно(пока обойдёмся без текстур):
Если объект стал прозрачным, значит что-то не так с текстурой или материалом, который был задан изначально.
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.