Unity как изменить skybox

In Unity, a skyboxA special type of Material used to represent skies. Usually six-sided. More infoSee in Glossary is a Material that uses a skybox ShaderA program that runs on the GPU. More infoSee in Glossary. For information on what skybox Shaders are available, see skybox Shaders.

In Unity, a skyboxA special type of Material used to represent skies. Usually six-sided. More info
See in Glossary
is a Material that uses a skybox ShaderA program that runs on the GPU. More info
See in Glossary
. For information on what skybox Shaders are available, see skybox Shaders.

Render pipeline compatibility

Feature Built-in Render PipelineA series of operations that take the contents of a Scene, and displays them on a screen. Unity lets you choose from pre-built render pipelines, or write your own. More info
See in Glossary
Universal Render Pipeline (URP) High Definition Render Pipeline (HDRP)
Skyboxes Yes (1) Yes (1) No (2)

Notes:

  1. The Built-in Render Pipeline, and the Universal Render Pipeline (URP) both exclusively use skyboxes to render a sky. These skyboxes are Materials that use a skybox Shader.
  2. The High Definition Render Pipeline (HDRP) does not support skybox Materials and instead includes multiple sky generation solutions.

Creating a skybox Material

To create a new skybox Material:

  1. From the menu bar, click Assets > Create > Material.
  2. In the Shader drop-down, click Skybox then the skybox Shader you want to use.
  3. You can now fill out the properties on the Material to set up the skybox. The properties available on the Material depend on the skybox Shader the Material uses.

Note: Each skybox Shader has its own set of prerequisite Textures that differ in number and Texture formatA file format for handling textures during real-time rendering by 3D graphics hardware, such as a graphics card or mobile device. More info
See in Glossary
. For information on the Textures a particular skybox Shader requires, see the documentation for that skybox Shader. You can find the list of skybox Shaders and their documentation on the skybox Shaders page.

Drawing a skybox in your Scene

After you create a skybox Material, you can render it in your SceneA Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary
. To do this:

  1. From the menu bar, click Window > Rendering > Lighting Settings.
  2. In the window that appears, click the Environment tab.
  3. Assign the skybox Material to the Skybox Material property.

This draws the skybox in the background of every CameraA component which creates an image of a particular viewpoint in your scene. The output is either drawn to the screen or captured as a texture. More info
See in Glossary
in your Scene. If you instead only want to draw the skybox for a particular Camera, see Drawing a skybox for a particular Camera.

Using a skybox Material for ambient light settings

After you create a skybox Material, Unity can use it to generate ambient lighting in your Scene. To make Unity do this:

  1. Open the Lighting window (menu: Window > Rendering > Lighting Settings).
  2. Assign your chosen skybox to the Skybox Material property.
  3. Click the Source drop-down and, from the list, click Skybox.

You can also specify when Unity updates the ambient lighting. To do this, change the Ambient Mode. The two values are:

  • Realtime: Unity constantly regenerates ambient lighting for your Scene. This is useful if you alter the skybox at run-time
  • Baked: Unity only generates ambient lighting for your Scene when you click the Generate Lighting button at the bottom of the Lighting window. This is useful if your skybox does not change during run-time because it saves computational resources.

Drawing a skybox for a particular Camera

If you only want to draw a skybox in the background of a particular Camera, use the Skybox component. When you attach this component to a GameObjectThe fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary
with a Camera, it overrides the skybox that the Camera draws. To attach and set up the Skybox component:

  1. Select a Camera in your Scene and view it in the InspectorA Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
    See in Glossary
    window.
  2. Click Add Component > Rendering > Skybox.
  3. On the Skybox component, assign the skybox Material to the Custom Skybox property.

Best Practices

If your Skybox includes a sun, moon, or other light in it, set up a Directional Light that points in the same direction as the light. This makes it appear as though the light in your skybox creates shadows in your Scene. If there are multiple Directional Lights in your Scene, you can choose which Directional Light the Skybox uses. To do this:

  1. From the menu bar, click Window > Rendering > Lighting Settings.
  2. Click the Scene tab.
  3. Assign the Directional Light you want to use to the Sun Source property.

If you want to have fog in your Scene, match the fog color to the color of the skybox. This makes the fog blend to the color of the Scene sky. To do this:

  1. From the menu bar, click Window > Rendering > Lighting Settings.
  2. Click the Environment tab.
  3. In the Other Settings section, enable the Fog checkbox.
  4. Set the Color property to a color that suits your skybox. For this, you can use the ink dropper tool to select a color from the Scene.

Предлагаю читателям «Хабрахабра» перевод публикации «Unity — Using Skyboxes» из блога компании Unity.

Дополнительные материалы к статье Skybox и Cubemap

Skybox является панорамной текстурой, которая находится за всеми объектами в сцене, что бы симулировать небо или большой город или любую другую перспективу на большом расстоянии (своего рода фон). Этот урок объясняет, как использовать skybox в Unity.

Что такое Skyboxes?

Skybox — панорамный вид разделенный на шесть текстур, представляющие шесть видимых направлений вдоль основных осей (вверх, вниз, влево, вправо, вперед и назад) (up, down, left, right, forward and backward). Если Skybox создан правильно, текстурные изображения будут как единое целое по краям, чтобы дать непрерывный окружающий образ, который можно рассматривать «изнутри» в любом направлении. Панорама оказывается позади всех остальных объектов в сцене и вращается в соответствии с текущей ориентации камеры (не путайте с положением камеры, которое всегда берется, чтобы быть в центре панорамы). Skybox таким образом, простой способ добавить реализма к сцене с минимальной нагрузкой на видеокарту.

Использование Skybox в Unity

Unity поставляется с рядом высококачественных Skybox в пакете Standard Assets (меню: Assets > Import Package > Skyboxes), но вы также можете подобрать подходящие наборы панорамных изображений из интернет-источников или создать свой собственный, используя программное обеспечение 3D-моделирования. Предполагаем, что вы уже имеете шесть текстур изображения для Skybox, вы должны импортировать их в Unity. После переходим к нашему skybox, затем переходим в панель Inspector. И устанавливаем его свойства, свойство Wrap Mode установим значение Clamp (если вы установите значение Repeat, края изображений не будут образовывать «бесшовную» текстуру).

image

Сам Skybox на самом деле тип материала, который использует один из шейдеров в подменю RenderFX. Если вы выберите Skybox Shader, вы увидите в панели инспектора (inspector), что то вроде следующего, с шестью примерами текстур:

image

Skybox Cubed шейдер работает в основном так же, но требует текстуры, которые будут добавлены к cubemap asset (меню:Assets > Create > Cubemap). Cubemap имеет шесть слотов текстур с теми же значения, как и Skybox в панели инспектора материалов (material inspector) .

После того, как он будет создан, вы можете установить новый Skybox, как Skybox по умолчанию (для всего проекта) в инспекторе настройки визуализации (меню: Edit> Render Settings). Вы можете переопределить Skybox по умолчанию для каждой камеры, назначив новый Skybox в компоненте Camera > Skybox (видно в инспекторе камеры).

Introduction — What is the Skybox in Unity?

The Sky­box is like an image that com­plete­ly sur­rounds a scene in Uni­ty and remains fixed no mat­ter how hard we try to get close to it. The pur­pose of the Sky­box is to rep­re­sent the dis­tant hori­zon of the scene and it is pos­si­ble to choose a tex­ture to do so.

In this arti­cle we will see how to change the Sky­box that comes by default in Uni­ty. This will allow us to cus­tomize the sky­box for our game. In the fol­low­ing video you can see the process.

ABOUT THIS VIDEO

In this video we see how to replace the DEFAULT SKY in UNITY using an envi­ron­ment texture.

HERE MY UNITY PLAYLIST
👇🏽

CONSIDER SUBSCRIBING TO THE CHANNEL

First Step — Get an HDR Texture to use as Skybox

To mod­i­fy the Sky­box of the scene we will need spe­cial tex­tures, one of them is the HDR (High Dynam­ic Range) tex­tures, they are tex­tures that have more infor­ma­tion than the ones we com­mon­ly use and they are use­ful to illu­mi­nate scenes, because you can increase or decrease their inten­si­ty and the tex­ture responds properly.

I usu­al­ly down­load tex­tures from the HDRI Haven page, they have a quite inter­est­ing gallery with this kind of images, the down­loads are free and you can also choose between qual­i­ties rang­ing from 1K to 8K tex­tures, as you can see in fig­ure 2.

HDRI Haven

How to change the Skybox in Unity — Step by Step

Before show­ing the com­plete process I will put a list of steps to sum­ma­rize the process, if you already have expe­ri­ence with Uni­ty you may find it useful.

1. Import the HDR tex­ture into Uni­ty and in the inspec­tor set its «Tex­ture Shape» para­me­ter to «Cube».

2. Cre­ate a new mate­r­i­al and set the Shad­er type as Sky­box > Cubemap.

3. Assign the HDR tex­ture to the «Cube­map HDR» field of our mate­r­i­al. With this we have the Sky­box ready to use it.

4. Go to the Win­dow > Ren­der­ing > Light­ing win­dow, Envi­ron­ment sec­tion and in the Sky­box field select the mate­r­i­al you have con­fig­ured in the pre­vi­ous step.

5. (Option­al) If the tex­ture does not have good qual­i­ty, mod­i­fy the com­pres­sion for­mat or down­load a high­er res­o­lu­tion HDR texture.

CHECK OUT THIS CRAZY EXPERIMENT

Detailed procedure on how to change the Skybox in Unity

Once we import the HDR tex­ture into Uni­ty we will cre­ate a new mate­r­i­al, in the Assets fold­er, right click, cre­ate and then select material.

creation window in unity, new material.
Fig. 3: We cre­ate a mate­r­i­al to make the Skybox.

We give it a name and then select it to see its prop­er­ties in the inspector.

hdr texture and skybox material in unity
Fig. 4: We select the mate­r­i­al to see its para­me­ters in the inspector.

In the head­er of the inspec­tor, we locate the field «Shad­er» which by default is set to «Stan­dard» and change it to the type Shad­er «Sky­box > Cube­map», as shown in fig­ures 5 and 6.

Now the inspec­tor for this mate­r­i­al will be shown with oth­er para­me­ters than before, as we see in fig­ure 7.

shader cubemap in unity
Fig. 7: This is what the new mate­r­i­al inspec­tor looks like.

In prin­ci­ple we are inter­est­ed in assign­ing our HDR tex­ture to the «Cube­map HDR» field but first we have to make some adjust­ments to the image. We select the HDR tex­ture that we have imported.

hdr texture and skybox material in unity
Fig. 8: We select the HDR tex­ture that we pre­vi­ous­ly import­ed to see its para­me­ters in the inspector.

We changed the «Tex­ture Shape» field to Cube and applied the changes

This will allow us to use the tex­ture for the Sky­box mate­r­i­al, we can either drag the tex­ture direct­ly into the field or press the «Select» but­ton and select it from the pop­up window.

If every­thing goes well, you should see a result like the one in fig­ure 13.

inspector window of a skybox cubemap material in unity with assigned sky texture
Fig. 13: With this you have the Sky­box ready to use.

Now that we have the Sky­box mate­r­i­al set up, let’s apply it to the scene. For that we have to open the «Light­ing» tab, in fig­ure 14 you can see where that win­dow is if you don’t have it open.

window unity lighting configuration
Fig. 14: We open the Light­ing win­dow to change the Skybox.

Inside the Light­ing win­dow we go to the «Envi­ron­ment» sec­tion and in the first field called «Sky­box Mate­r­i­al» we assign the Sky­box mate­r­i­al that we have pre­vi­ous­ly configured.

In fig­ure 17 you can see the first result of doing this, the tex­ture does not look good at all due to the type of compression.

change of skybox in unity, hdr texture has low quality
Fig. 17: First result, the Sky­box is applied but the image has a cer­tain qual­i­ty loss.

We can select it and in the inspec­tor change the com­pres­sion to «RGB 16», «RGB 24» or «RGBA 32», this will bring an increase in the qual­i­ty but also in the weight of the image. You can try down­load­ing dif­fer­ent qual­i­ties of HDR tex­ture and try dif­fer­ent for­mats to find a bal­ance between qual­i­ty and performance.

texture configuration in unity, rgba 32 format
Fig. 18: We select the HDR tex­ture and mod­i­fy the format.

In fig­ure 19 we see the final result that I have reached. Now that we have changed the new Sky­box in the scene, we will be able to do light­ing bakes to get bet­ter results.

change of skybox in unity, hdr texture has good quality
Fig. 19: The qual­i­ty has improved but so has the weight of the image.

В Unity – небесный ящикОсобый тип материала, используемый для представления неба. Обычно шестигранник. Подробнее
See in Словарь
— это Материал, в котором используется скайбокс ШейдерПрограмма, работающая на графическом процессоре. Подробнее
См. в Словарь
. Информацию о доступных шейдерах скайбокса см. в разделе шейдеры скайбокса.

Совместимость конвейера рендеринга

Характерная черта Встроенный конвейер рендеринга Универсальный конвейер рендеринга (URP) Конвейер рендеринга высокого разрешения (HDRP)
Skyboxes Да (1) Да (1) Нет (2)

Примечания:

  1. Встроенный конвейер рендеринга и Универсальный конвейер рендеринга (URP) оба используют исключительно скайбоксы для рендеринга неба. Эти скайбоксы представляют собой материалы, в которых используется шейдер скайбокса.
  2. Конвейер рендеринга высокого разрешения (HDRP) не поддерживает материалы скайбокса и вместо этого включает несколько решений для создания неба.

Создание материала для скайбокса

Чтобы создать новый материал скайбокса:

  1. В строке меню нажмите Ресурсы > Создать > Материал.
  2. В раскрывающемся списке Шейдер нажмите Skybox, а затем шейдер Skybox, который вы хотите использовать.
  3. Теперь вы можете заполнить свойства материала, чтобы настроить скайбокс. Свойства, доступные для материала, зависят от шейдера скайбокса, который использует материал.

Примечание. Каждый шейдер скайбокса имеет собственный набор необходимых текстур, которые различаются номером и форматом текстурыПодробнее
См. в Словарь
. Информацию о текстурах, требуемых для конкретного шейдера скайбокса, см. в документации к этому шейдеру скайбокса. Вы можете найти список шейдеров скайбокса и документацию по ним на странице шейдеров скайбокса.

Отрисовка скайбокса в вашей сцене

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

  1. В строке меню нажмите Окно > Рендеринг > Настройки освещения.
  2. В появившемся окне перейдите на вкладку Сцена.
  3. Назначьте материал скайбокса свойству Материал скайбокса.

При этом на фоне каждой Камерыкомпонента, который создает изображение определенной точки обзора в вашей сцене, отображается скайбокс. Вывод либо рисуется на экране, либо фиксируется в виде текстуры. Подробнее
См. Словарь
в вашей сцене. Если вместо этого вы хотите нарисовать скайбокс только для определенной камеры, см. раздел Рисование скайбокса для конкретной камеры.

Использование материала скайбокса для настройки внешнего освещения

После того как вы создадите материал скайбокса, Unity может использовать его для создания окружающего освещения в вашей сцене. Чтобы заставить Unity сделать это:

  • Откройте окно Освещение (меню: Окно > Рендеринг > Настройки освещения).
  • Назначьте выбранный скайбокс свойству Материал скайбокса.
  • Нажмите раскрывающееся меню Источник и в списке выберите Skybox.
  • Вы также можете указать, когда Unity будет обновлять окружающее освещение. Для этого измените Ambient Mode. Два значения:

    • В реальном времени: Unity постоянно восстанавливает окружающее освещение для вашей сцены. Это полезно, если вы изменяете скайбокс во время выполнения.
    • Запеченное: Unity создает окружающее освещение для вашей сцены только тогда, когда вы нажимаете кнопку Создать освещение в нижней части окна Освещение. Это полезно, если ваш скайбокс не меняется во время выполнения, потому что это экономит вычислительные ресурсы.

    Отрисовка скайбокса для конкретной камеры

    Если вы хотите нарисовать скайбокс только на фоне определенной камеры, используйте компонент Skybox. Когда вы присоединяете этот компонент к GameObjectфундаментальному объекту в сценах Unity, который может представлять персонажей, реквизит, декорации, камеры, путевые точки , и больше. Функциональность GameObject определяется прикрепленными к нему компонентами. Подробнее
    См. в Словарь
    с камерой, он переопределяет скайбокс, который рисует камера. Чтобы подключить и настроить компонент Skybox:

    1. Выберите камеру в своей сцене и просмотрите ее в инспектореокне Unity, в котором отображается информация о выбранном в данный момент игровом объекте, настройки актива или проекта, что позволяет просматривать и редактировать значения. Дополнительная информация
      См. в окне Словарь
      .
    2. Нажмите Добавить компонент > Рендеринг > Skybox.
    3. В компоненте Skybox назначьте Материал Skybox свойству Пользовательский Skybox.

    Рекомендации

    Если в вашем скайбоксе есть солнце, луна или другой источник света, установите направленный источник света, направленный в том же направлении, что и источник света. Это создает впечатление, что свет в вашем скайбоксе создает тени в вашей сцене. Если в вашей сцене есть несколько направленных источников света, вы можете выбрать, какой из них использует скайбокс. Для этого:

    1. В строке меню нажмите Окно > Рендеринг > Настройки освещения.
    2. Перейдите на вкладку Сцена.
    3. Назначьте направленный свет, который вы хотите использовать, свойству Sun Source.

    Если вы хотите, чтобы в вашей сцене был туман, сопоставьте цвет тумана с цветом скайбокса. Это заставляет туман сливаться с цветом неба сцены. Для этого:

    1. В строке меню нажмите Окно > Рендеринг > Настройки освещения.
    2. Перейдите на вкладку Сцена.
    3. В разделе Другие настройки установите флажок Туман.
    4. Установите для свойства Color цвет, который подходит вашему скайбоксу. Для этого вы можете использовать инструмент «Пипетка», чтобы выбрать цвет из сцены.
Skip to content

Unity3D How To Change Skybox With Script

Unity3D How To Change Skybox With Script

Unity3D How To Change Skybox With Script 

I wanted to change the skybox when a certain event happened. In my case, I wanted a new, random skybox each time a new enemy appeared to fight. First, I will show you how to change the skybox. Second, I will show you how to choose a random skybox and use it. Both scripts are stand alone so choose what works best for you.

To change the skybox using a c# script you have to store the skybox material reference in the Inspector and then assign it during runtime.

Create a public material, save the script to a GameObject, and then drag/drop the skybox material in your Inspector.

Further down in your Start or a function that you call in your code, make the change:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeSkybox : MonoBehaviour {

 public Material skybox1;

 // Use this for initialization
 void Start () {
    RenderSettings.skybox = skybox1;
 }
 
 // Update is called once per frame
 void Update () { 
 }
}

That is it. Next I’ll add a few changes to choose a random skybox each time. Using the following code, you will need to select the script or GameObject with the script attached and look for the “skyboxes” array in the Inspector. Click the arrow to expand it and change the 0 to however many skybox materials you have. Now you’ll have a few fields to drag/drop your skybox materials. The following script will choose one randomly at start up. To make the random change again, simply call the function ChangeMySkybox();

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeSkybox : MonoBehaviour {

public Material[] skyboxes;

// Use this for initialization
 void Start () {
    ChangeMySkybox();
 }
 
 // Update is called once per frame
 void Update () { 
 }

void ChangeMySkybox()
 {
    int x = Random.Range(0, skyboxes.Length - 1);
    RenderSettings.skybox = skyboxes[x];
 }
}


Unity3D How To Change Skybox With Script

Share This Story, Choose Your Platform!

Related Posts

Page load link

Go to Top

Предлагаю читателям «Хабрахабра» перевод публикации «Unity — Using Skyboxes» из блога компании Unity.

Skybox является панорамной текстурой, которая находится за всеми объектами в сцене, что бы симулировать небо или большой город или любую другую перспективу на большом расстоянии (своего рода фон). Этот урок объясняет, как использовать skybox в Unity.

Что такое Skyboxes?

Skybox — панорамный вид разделенный на шесть текстур, представляющие шесть видимых направлений вдоль основных осей (вверх, вниз, влево, вправо, вперед и назад) (up, down, left, right, forward and backward). Если Skybox создан правильно, текстурные изображения будут как единое целое по краям, чтобы дать непрерывный окружающий образ, который можно рассматривать «изнутри» в любом направлении. Панорама оказывается позади всех остальных объектов в сцене и вращается в соответствии с текущей ориентации камеры (не путайте с положением камеры, которое всегда берется, чтобы быть в центре панорамы). Skybox таким образом, простой способ добавить реализма к сцене с минимальной нагрузкой на видеокарту.

Использование Skybox в Unity

Unity поставляется с рядом высококачественных Skybox в пакете Standard Assets (меню: Assets > Import Package > Skyboxes), но вы также можете подобрать подходящие наборы панорамных изображений из интернет-источников или создать свой собственный, используя программное обеспечение 3D-моделирования. Предполагаем, что вы уже имеете шесть текстур изображения для Skybox, вы должны импортировать их в Unity. После переходим к нашему skybox. И устанавливаем его свойства, Wrap Modeустановим Clamp, если вы установите Repeat (края изображений не будут образовывать «бесшовную» текстуру).

image

Сам Skybox на самом деле тип материала, который использует один из шейдеров в подменю RenderFX. Если вы выберите Skybox Shader, вы увидите в панели инспектора (inspector), что то вроде следующего, с шестью примерами текстур:

image

Skybox Cubed шейдер работает в основном так же, но требует текстуры, которые будут добавлены к cubemap asset (меню:Assets > Create > Cubemap). Cubemap имеет шесть слотов текстур с теми же значения, как и Skybox в панели инспектора материалов (material inspector) .

После того, как он будет создан, вы можете установить новый Skybox, как Skybox по умолчанию (для всего проекта) в инспекторе настройки визуализации (меню: Edit> Render Settings). Вы можете переопределить Skybox по умолчанию для каждой камеры, назначив новый Skybox в компоненте Camera > Skybox (видно в инспекторе камеры).

Автор: patch1

Источник

Понравилась статья? Поделить с друзьями:
  • Unitale error sans
  • Unit warning chk then reset магнитола jvc выдает ошибку
  • Unit file format error
  • Uninstallmonitor exe ошибка при запуске приложения
  • Unins000 msg is missing как исправить