Как воспроизвести видео в unity
Video overview
Use Unity’s video system to integrate video into your game. Video footage can add realism, save on rendering The process of drawing graphics to the screen (or to a render texture). By default, the main camera in Unity renders its view to the screen. More info
See in Glossary complexity, or help you integrate content available externally.
To use video in Unity, import Video Clips and configure them using the Video Player component. The system allows you to feed video footage directly into the Texture An image used when rendering a GameObject, Sprite, or UI element. Textures are often applied to the surface of a mesh to give it visual detail. More info
See in Glossary parameter of any component A functional part of a GameObject. A GameObject can contain any number of components. Unity has many built-in components, and you can create your own by writing scripts that inherit from MonoBehaviour. More info
See in Glossary that has one. Unity then plays the Video on that Texture at run time.
A Video Player component (shown in the Inspector window with a Video Clip assigned, right) attached to a spherical GameObject (shown in the Game view, left).
Unity’s video features include the hardware-accelerated and software decoding of Video files, transparency support, multiple audio tracks, and network streaming.
2017–06–15 Page published
Video player support for PS4 added in 2017.1 NewIn20171
Unity 5. Видеоплеер
Как добавить видео в Unity 5.
Сегодня я хочу показать вам, как использовать компонент Video Player в бесплатном движке для создания игр Unity 5. Компонент Video Player позволяет использовать видео в создании игр, например при создании заставок, или при использовании игровых объектов, которые должны отображать видео.
Первым делом установим программу QuickTime, которая поможет Unity в конвертации видео и отображении компонента Video Player. Скачать программу можно ниже в архиве.
Далее создадим новый проект в Unity. Для начала можно показать вам как отображаются видео на игровых объектах. Я создал модель простенького телевизора и поместил его в Unity на сцену.
У этого объекта экран идет отдельным объектом (дочерним), с которым мы и будем работать. На этот экран поместим компонент Video Player и Audio Source и займемся самим видеороликом.
Подготовьте видеоролик формата .mov, .mpg, .mpeg, .mp4, .avi, .asf и перетащите его в unity. После копирования в inspector появятся свойства нашего видео, где можно откорректировать несколько функций, изменить формат отображения, включить или отключить импорт звука, повернуть видео по вертикали или по горизонтали. Я думаю сложностей здесь возникнуть не должно. Но помните, разрешение видео не будет автоматически корректироваться по размеру игрового объекта, поэтому следует подстраивать разрешение видео вручную. Поставьте галочку у поля Transcode и в строке Dimensions выберете нужное разрешение.
Вернемся к нашему телевизору, точнее к экрану на котором находится компонент Video Player. В свойствах этого объекта есть строка Video Clip куда и следует перетащить наш видеоролик.
Вот описание остальных функций:
Play on Awake – Воспроизводит видео при запуске сцены,
Loop – повтор ролика,
Playback Speed – скорость проигрывания ролика,
Render mode – можно настроить способ отображение ролика, с меша игрового объекта, либо напрямую на камеру, миную все игровые объекты на сцене, либо на заднем плане,
В строке Audio Source указывается компонент Audio source, который мы добавили на этот же объект для воспроизведения звуковой дорожки, которую мы импортировали вместе с видео.
На этом этапе можно запустить сцену и мы увидим как на экране модели телевизора будет воспроизводится наш ролик.
Для создания видео сцены просто на пустой сцене создайте пустой игровой объект и добавьте к нему компонент Video Player. В настройка компонента в Render Mode выберете, к примеру Camera Near Plane и в появившейся строке укажите главную камеру.
Скачать модель телевизора и программу QuickTime вы можете здесь.
Web Player Streaming
Web Player Streaming is critical for providing a great web gaming experience for the end user. The idea behind web games is that the user can view your content almost immediately and start playing the game as soon as possible instead of making them wait for a progress bar. This is very achievable, and we will explain how.
Tuning for Portals
This section will focus on publishing to online game portals. Streaming is useful for all kinds of contents, and it can easily be applied to many other situations.
Online game portals expect that some form of game play really starts after downloading at most 1 MB of data. If you don’t reach this, it makes it that much less likely for a portal to accept your content. From the user’s perspective, the game needs to start quickly. Otherwise their time is being wasted and they might as well close the window.
On a 128 kilobit cable connection you can download 16 KB per second or 1 MB per minute. This is the low end of bandwidth online portals target.
The game would optimally be set up to stream something like this:
The key point to keep in mind is to think in wait times for a user on a slow connection. Never let them wait.
Now, don’t panic if your web player currently is 10 MB. It seems daunting to optimize it, but it turns out that with a little effort it is usually quite easy to structure your game in this fashion. Think of each above step as an individual scene. If you’ve made the game, you’ve done the hard part already. Structuring some scenes around this loading concept is a comparative breeze!
This game could use a little more optimization! For more information, we recommend you read the reducing file size page.
The Most Important Steps
Load the menu first. Showing an animated logo is a great way to make time go by unnoticed, thus letting the download progress further.
Make the first level be short and not use a lot of assets. This way, the first level can be loaded quickly, and by keeping the player occupied playing it for a minute or two you can be sure that the download of all remaining assets can be completed in the background. Why not have a mini tutorial level where the user can learn the controls of the game? No reason for high-res textures here or loads of objects, or having all your enemies in the first level. Use the one with the lowest poly-count. And yes, this means you might have to design your game with the web player experience in mind.
There is no reason why all music must be available when the game starts. Externalize the music and load it via the WWW class. Unity compresses audio with the high quality codec, Ogg Vorbis. However even when compressed, audio takes up a lot of space, and if you have to fit things into 3 MB, if you have 5 minutes of music all the compression in the world won’t save you. Sacrifices are needed. Load a very short track that you can loop until more music has been downloaded. Only load more music when the player is hooked on the first level.
Optimize your textures using their Import Settings. After you externalize music, textures easily take up 90% of the game. Typical texture sizes are too big for web deployment. In a small browser window, sometimes big textures don’t even increase the visual fidelity at all. Make sure you use textures that are only as big as they must be (and be ready for more sacrifices here). Halving the texture resolution actually makes the texture size a quarter of what it was. And of course all textures should be DXT compressed.
Generally reduce the size of your web players. There is a manual page committed to the utilities Unity offers for optimizing file size here. Although Unity uses cutting edge LZMA-based compression which usually compresses game data to anywhere from one half to a third of the uncompressed size, you’ll need to try everything you can.
Try to avoid Resources.Load. While Resources.Load can be very handy, Unity will not be able to order your assets by when they are first used when you use Resources.Load, because any script could attempt to load the Resource. You can set which level will include all assets that can be loaded through Resources.Load in the Edit->Project Settings->Player using the First Streamed Level With Resources property. Obviously you want to move Resources.Load assets as late as possible into the game or not use the feature at all.
Publishing Streaming Web Players
Streaming in Unity is level based, and there is an easy workflow to set this up. Internally, Unity does all the dirty work of tracking assets and organizing them in the compressed data files optimally, ordering it by the first scene that uses them. You simply have to ensure that the first levels in the Build Settings use as few assets as possible. This comes naturally for a “menu level”, but for a good web experience you really need make sure that the first actual game levels the player is going to play are small too.
In order to use streaming in Unity, you select Web Player Streamed in the Build Settings. Then the content automatically starts as soon as all assets used by the first level are loaded. Try to keep the “menu level” to something like 50–100 KB. The stream continues to load as fast as it can, and meanwhile live decompresses. When you look at the Console during/after a build, you can see how large the streamed data is.
You can query the progress of the stream by level, and once a level is available it can be loaded. Use GetStreamProgressForLevel for displaying a progress bar and CanStreamedLevelBeLoaded to check if all the data is available to load a specific level.
Потоковая загрузка в веб-плеере
Проще говоря, со включенной потоковой загрузкой пользователи смогут начать игру быстрее, чем когда-либо.
Необходимо лишь следить за тем, чтобы загрузка новой сцены происходила лишь после завершения потоковой загрузки.
Как правило, вы используете такой код для загрузки уровня в проигрывателях без потоковой загрузки:
В веб-проигрывателе с потоковой загрузкой сперва следует убедиться, что потоковая загрузка уровня завершена. Это осуществляется с помощью метода CanStreamedLevelBeLoaded(). Вот как это работает:
Если вы желаете отобразить игроку прогресс потоковой загрузки уровня, то вы можете считывать его с помощью метода GetStreamProgressForLevel() для отображения в шкале загрузки или другом представлении прогресса.
Video Player component
The screenshot below shows a Video Player component attached to a spherical GameObject.
By default, the Material Property of a Video Player component is set to MainTex, which means that when the Video Player component is attached to a GameObject that has a Renderer, it automatically assigns itself to the Texture on that Renderer (because this is the main Texture for the GameObject). Here, the GameObject has a Mesh Renderer_ A mesh component that takes the geometry from the Mesh Filter and renders it at the position defined by the object’s Transform component. More info
See in Glossary component, so the Video Player automatically assigns it to the Renderer field, which means the Video Clip plays on the Mesh__ The main graphics primitive of Unity. Meshes make up a large part of your 3D worlds. Unity supports triangulated or Quadrangulated polygon meshes. Nurbs, Nurms, Subdiv surfaces must be converted to polygons. More info
See in Glossary Renderer’s Texture.
A Video Player component attached to a spherical GameObject, playing the Video Clip on the GameObject’s main Texture (in this case, the Texture of the Mesh Renderer)
You can also set a specific target for the video to play on, including:
A Material An asset that defines how a surface should be rendered. More info
See in Glossary Texture parameter
Any Texture field in a component
VideoPlayer component Reference
The Video Player component
Property | Function | ||
---|---|---|---|
Source | Choose the type of source for your video. | ||
Video Clip | Assign a Video Clip to the Video Player. | ||
Video Clip | Use this field to define the Video Clip assigned to the Video Player component. Drag-and-drop the video file into this field, or click the circle to the right of the field and choose it from a list of Assets if it is in your Project folder. | ||
URL | Assign a video from a URL (for example, http:// or file://). Unity reads the video from this URL at run time. | ||
URL | Enter the URL of the video you want to assign to the Video Player. | ||
Browse… | Click this to quickly navigate your the local file system and open URLs that begin file://. | ||
Play On Awake Set this to true to make an Audio Source start playing on awake More info See in Glossary | Tick the Play On Awake checkbox to play the video the moment the Scene A 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 launches. Untick it if you want to trigger the video playback at another point during run time. Trigger it via scripting with the Play() command. | ||
Wait For First Frame | If you tick the Wait For First Frame checkbox, Unity waits for the first frame of the source video to be ready for display before the game starts. If you untick it, the first few frames might be discarded to keep the video time in sync with the rest of the game. | ||
Loop | Ticking the Loop checkbox to make the Video Player component loop the source video when it reaches its end. If this is unticked, the video stops playing when it reaches the end. | ||
Playback Speed | This slider and numerical field represent a multiplier for the playback speed, as a value between 0 and 10. This is set to 1 (normal speed) by default. If the field is set to 2, the video plays at two times its normal speed. | ||
Render Mode | Use the drop-down to define how the video is rendered. | ||
Camera Far Plane | Render the video on the Camera’s far plane. | ||
Camera Near Plane | Render the video on the Camera’s near plane. | ||
Camera A 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 | Define the Camera receiving the video. | ||
Alpha | The global transparency level added to the source video. This allows elements behind the plane to be visible through it. See documentation on video transparency support for more information about alpha channels. | ||
Render Texture A special type of Texture that is created and updated at runtime. To use them, first create a new Render Texture and designate one of your Cameras to render into it. Then you can use the Render Texture in a Material just like a regular Texture. More info See in Glossary | Render the video into a Render Texture. | ||
Target Texture | Define the Render Texture where the Video Player component renders its images. | ||
Material Override | Render the video into a selected Texture property of a GameObject through its Renderer’s Material. | ||
Renderer | The Renderer where the Video Player component renders its images. When set to None, the Renderer on the same GameObject as the Video Player component is used. | ||
Material Property | The name of the Material Texture property that receives the Video Player component images. | ||
API Only | Render the video into the VideoPlayer.texture Scripting API property. You must use scripting to assign the Texture to its intended destination. | ||
Aspect Ratio The relationship of an image’s proportional dimensions, such as its width and height. See in Glossary | The aspect ratio of the images that fill the Camera Near Plane, Camera Far Plane or Render Texture when the corresponding Render Mode is used. | ||
No Scaling | No scaling is used. The video is centered on the destination rectangle. | ||
Fit Vertically | Scale the source to fit the destination rectangle vertically, cropping the left and right sides or leaving black areas on each side if necessary. The source aspect ratio is preserved. | ||
Fit Horizontally | Scale the source to fit the destination rectangle horizontally, cropping the top and bottom regions or leaving black areas above and below if needed. The source aspect ratio is preserved. | ||
Fit Inside | Scale the source to fit the destination rectangle without having to crop. Leaves black areas on the left and right or above and below as needed. The source aspect ratio is preserved. | ||
Fit Outside | Scale the source to fit the destination rectangle without leaving black areas on the left and right or above and below, cropping as required. The source aspect ratio is preserved. | ||
Stretch | Scale both horizontally or vertically to fit the destination rectangle. The source aspect ratio is not preserved. | ||
Audio Output Mode | Define how the source’s audio tracks are output. | ||
None | Audio is not be played. | ||
Audio Source A component which plays back an Audio Clip in the scene to an audio listener or through an audio mixer. More info See in Glossary | Audio samples are sent to selected audio sources, enabling Unity’s audio processing to be applied. | ||
Direct | Audio samples are sent directly to the audio output hardware, bypassing Unity’s audio processing. | ||
API Only (Experimental) | Audio samples are sent to the associated AudioSampleProvider. | ||
Controlled Tracks | The number of audio tracks in the video. Only shown when Source is URL. When Source is Video Clip, the number of tracks is determined by examining the video file. | ||
Track Enabled | When enabled by ticking the relevant checkbox, the associated audio track is used for playback. This must be set prior to playback. The text to the left of the checkbox provides information about the audio track, specifically the track number, language, and number of channels. For example, in the screenshot above, this text is Track 0 [und. 1 ch]. This means it is the first track (Track 0), the language is undefined (und.), and the track has one channel (1 ch), meaning it is a mono track. When the source is a URL, this information is only available during playback. This property only appears if your source is a Video Clip that has an audio track (or tracks), or your source is a URL (allowing you to indicate how many tracks are expected from the URL during playback). | ||
Audio Source | The audio source through which the audio track is played. The targeted audio source can also play Audio Clips. The audio source’s playback controls ( Play On Awake and Play() in scripting API) do not apply to the video source’s audio track. This property only appears when the Audio Output Mode is set to Audio Source. | ||
Mute | Mute the associated audio track. In Audio Source mode, the audio source’s control is used. This property only appears when the Audio Output Mode is set to Direct. | ||
Volume | Volume of the associated audio track. In Audio Source mode, the audio source’s volume is used. This property only appears when the Audio Output Mode is set to Direct. |
Video Player Scripting Example
The following script demonstrates a few of the VideoPlayer component’s features.
Как добавить видео в Unity 5
Сегодня я хочу показать вам, как использовать компонент Video Player в бесплатном движке для создания игр Unity 5. Компонент Video Player позволяет использовать видео в создании игр, например при создании заставок, или при использовании игровых объектов, которые должны отображать видео.
Первым делом установим программу QuickTime, которая поможет Unity в конвертации видео и отображении компонента Video Player. Скачать программу можно ниже в архиве.
Далее создадим новый проект в Unity. Для начала можно показать вам как отображаются видео на игровых объектах. Я создал модель простенького телевизора и поместил его в Unity на сцену.
У этого объекта экран идет отдельным объектом (дочерним), с которым мы и будем работать. На этот экран поместим компонент Video Player и Audio Source и займемся самим видеороликом.
Подготовьте видеоролик формата .mov, .mpg, .mpeg, .mp4, .avi, .asf и перетащите его в unity. После копирования в inspector появятся свойства нашего видео, где можно откорректировать несколько функций, изменить формат отображения, включить или отключить импорт звука, повернуть видео по вертикали или по горизонтали. Я думаю сложностей здесь возникнуть не должно. Но помните, разрешение видео не будет автоматически корректироваться по размеру игрового объекта, поэтому следует подстраивать разрешение видео вручную. Поставьте галочку у поля Transcode и в строке Dimensions выберете нужное разрешение.
Вернемся к нашему телевизору, точнее к экрану на котором находится компонент Video Player. В свойствах этого объекта есть строка Video Clip куда и следует перетащить наш видеоролик.
Вот описание остальных функций:
Play on Awake – Воспроизводит видео при запуске сцены,
Loop – повтор ролика,
Playback Speed – скорость проигрывания ролика,
Render mode – можно настроить способ отображение ролика, с меша игрового объекта, либо напрямую на камеру, миную все игровые объекты на сцене, либо на заднем плане,
В строке Audio Source указывается компонент Audio source, который мы добавили на этот же объект для воспроизведения звуковой дорожки, которую мы импортировали вместе с видео.
На этом этапе можно запустить сцену и мы увидим как на экране модели телевизора будет воспроизводится наш ролик.
Для создания видео сцены просто на пустой сцене создайте пустой игровой объект и добавьте к нему компонент Video Player. В настройка компонента в Render Mode выберете, к примеру Camera Near Plane и в появившейся строке укажите главную камеру.
Скачать модель телевизора и программу QuickTime вы можете здесь.