This page has been translated automatically.
Видеоуроки
Интерфейс
Основы
Продвинутый уровень
Подсказки и советы
Основы
Программирование на C#
Рендеринг
Профессиональный уровень (SIM)
Принципы работы
Свойства (properties)
Компонентная Система
Рендер
Физика
Редактор UnigineEditor
Обзор интерфейса
Работа с ассетами
Контроль версий
Настройки и предпочтения
Работа с проектами
Настройка параметров ноды
Setting Up Materials
Настройка свойств
Освещение
Sandworm
Использование инструментов редактора для конкретных задач
Расширение функционала редактора
Встроенные объекты
Ноды (Nodes)
Объекты (Objects)
Эффекты
Декали
Источники света
Geodetics
World-ноды
Звуковые объекты
Объекты поиска пути
Player-ноды
Программирование
Основы
Настройка среды разработки
Примеры использования
C++
C#
UnigineScript
UUSL (Unified UNIGINE Shader Language)
Плагины
Форматы файлов
Материалы и шейдеры
Rebuilding the Engine Tools
Интерфейс пользователя (GUI)
Двойная точность координат
API
Animations-Related Classes
Containers
Common Functionality
Controls-Related Classes
Engine-Related Classes
Filesystem Functionality
GUI-Related Classes
Math Functionality
Node-Related Classes
Objects-Related Classes
Networking Functionality
Pathfinding-Related Classes
Physics-Related Classes
Plugins-Related Classes
IG Plugin
CIGIConnector Plugin
Rendering-Related Classes
VR-Related Classes
Работа с контентом
Оптимизация контента
Материалы
Визуальный редактор материалов
Material Nodes Library
Miscellaneous
Input
Math
Matrix
Textures
Art Samples
Учебные материалы

Воспроизведение фоновой музыки

The game must output some audio besides the bullet hit sound effect. To play the background music we will use the component system once again.Игра должна выводить какой-то звук, помимо звукового эффекта попадания пули. Для воспроизведения фоновой музыки мы снова будем использовать компонентную систему.

Let's create the node with a Music Player component that plays the looped music from the game start.Давайте создадим ноду с компонентом Music Player, который воспроизводит зацикленную музыку с самого начала игры.

  1. Create a new C# component and call it MusicPlayer. Open your IDE and copy the code below. Save your code in the IDE to ensure it's automatic compilation on switching back to UnigineEditor.Создайте новый компонент C# и назовите его MusicPlayer. Откройте свою среду разработки и скопируйте приведенный ниже код. Сохраните свой код в IDE, чтобы обеспечить его автоматическую компиляцию при возврате к UnigineEditor.

    MusicPlayer.cs
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using Unigine;
    
    [Component(PropertyGuid = "AUTOGENERATED_GUID")] // <-- this line is generated automatically for a new component
    public class MusicPlayer : Component
    {
    	public AssetLink backgroundMusic;
    	
    	AmbientSource music;
     
    	void Init()
    	{
    		// check if the backgroundMusic is set and the file asset exists
    		if (backgroundMusic.IsFileExist)
    		{
    			music = new AmbientSource(backgroundMusic.Path);
    			music.Loop = 1;
    			music.Gain = 0.5f;
    			// start playing the music on initialization
    			music.Play();
    		}
    
    	}
    
    	void Shutdown()
    	{
    		if (music.IsValidPtr)
    			music.DeleteLater(); 
    	}
    }
  2. Create a new Dummy Node, rename it to "music_player", and place it somewhere in the world.Создайте новую Dummy Node, переименуйте ее в "music_player" и поместите ее где-нибудь в мире.
  3. Add the MusicPlayer component to the music_player node.Добавьте компонент MusicPlayer к ноде music_player.
  4. Assign the imported music asset (programming_quick_start/music/ost.mp3) to the Background Music field of the MusicPlayer component.Назначьте импортированный музыкальный ассет (programming_quick_start/music/ost.mp3) полю Background Music компонента MusicPlayer.

  5. Save changes to the world, go to File->Save World or press Ctrl+S hotkey.Сохраните изменения в мире, перейдите к File->Save World или нажмите горячую клавишу Ctrl+S.
  6. Run the project in the UnigineEditor to check out the background music.Запустите проект в UnigineEditor, чтобы проверить фоновую музыку.

Последнее обновление: 19.04.2024
Build: ()