With recent Unity versions (2020, 2021 and 2022) Flutter Android builds will take a lot longer, because it also has to compile the IL2CPP code from Unity.
From the Readme:
Android builds takes forever to complete Unity 2022.1.*, remove these lines from unityLibrary/build.gradle filecommandLineArgs.add("--enable-debugger") commandLineArgs.add("--profiler-report") commandLineArgs.add("--profiler-output-file=" + workingDir + "/build/il2cpp_"+ abi + "_" + configuration + "/il2cpp_conv.traceevents")
Here is some testing to check how to speed things up.
Or C#EditorUserBuildSettings.il2CppCodeGeneration = UnityEditor.Build.Il2CppCodeGeneration.OptimizeSize;
C++ compiler configuration
InPlayer settings -> Other settings -> configuration, selectDebug.
Or C#PlayerSettings.SetIl2CppCompilerConfiguration(BuildTargetGroup.Android, Il2CppCompilerConfiguration.Debug);
Disable script debugging
Don't bother setting this in the Unity settings, it will be overridden by the build script. Assets/FlutterUnityIntegration/Editor/build.cs In the functionDoBuildAndroid()remove the line enabling script debugging. playerOptions.options = BuildOptions.AllowDebugging; This is the same as removingcommandLineArgs.add("--enable-debugger")from the build.gradle file after an export.
Measuring results
When you run a Flutter build, there are multiple IL2CPP stages that report their duration, with 2 sections taking far longer than all others. We can compare these build durations when using different settings in Unity.
The exact durations here aren't important, as this will be different of every computer and project setup. This is afterflutter cleanand a fresh Unity export. Any subsequent runs will be faster because of caching.
Flutter build apk, with an export from Unity 2021.3.5f1 inandroid/unityLibraryon Windows 10.
Settingarmv7 durationarm64 duration
example project
2m:04s
2m:03s
1 - Code generation (faster builds)
1m:41s
1m:38s
2 - Compiler configuration (debug)
45s
43s
3 - No script debugging
30s
30s
1 + 2
35s
34s
1 + 2 + 3
23s
25s
Conclusion
My advice is to add this to the build script inDoBuildAndroid()for any test or debug builds, remove it for final release builds.
빌트인 프로파일러 모듈로, 애플리케이션이 메모리를 사용하는 위치에 대한 기본 정보를 제공합니다.
메모리 프로파일러 모듈은 애플리케이션에 할당된 전체 메모리를 나타내는 카운터를 시각화합니다. 메모리 모듈을 사용하여 로드된 오브젝트의 수와 카테고리 별로 해당 오브젝트가 차지하는 메모리 양과 같은 정보를 볼 수 있습니다.
2. Memory Profiler 1.0 (필수)
Unity 애플리케이션 및 Unity 에디터의 메모리 사용량을 검사하는 데 사용할 수 있는 도구로, 어떤 에셋이 메모리를 사용하고 있는지 애플리케이션의 메모리 할당에 대한 정보를 자세하게 확인할 수 있습니다. 특히 Unity 에디터에 메모리 프로파일러 창을 추가하여 메모리 스냅샷을 캡처, 검사 및 비교할 수 있습니다.
Today we’ll be talking about the Preload Audio Data option in Unity’s Audio Import Settings and why understanding this small but critical checkbox is important foryour game.
So many options… How does Unity choose which audio is loaded to a scene?
Editor’s Note: Compression Formats, Load Type and the Preload Audio Data/Load in Background settings go hand in hand. We recommend reading our blog posts on all three in the following order for a complete overview:
This blog post has been made as a supplement to our video tutorial on this same topic.
Introduction
After figuring out how Unity compresses your audio with the different compression formats, and primes your audio for playing with the different Load Type settings, the next question to answer is: What does the Preload Audio Data option do?
The Unity Documentation provides important information on this subject, but it doesn’t explain exactly when and how audio files are selected to be loaded in an active scene.
Preload Audio Data
Here’s Unity’s definition of Preload Audio Data from their manual:
If enabled, the audio clip will be pre-loaded when the scene is loaded. This is on by default to reflect standard Unity behavior where all AudioClips have finished loading when the scene starts playing.
This information is pretty clear already. If you choose this option, you want the audio priming process with the respective Load Types to take placebefore the scene is activated and becomes playable.
This will result in mission-critical audio files being ready to be played at all times at the expense of making the scene load time a little bit longer.
So far, so good. But there is one question left unanswered:
How does Unity decide which Audio is going to be loaded in which Scene?
References
Let’s imagine this situation: you’re developing a large game that has 15 hours of playtime and around 30 scenes. You have something like 1000 SFX and 2000 dialogue files. You wouldnotwant every single audio asset marked with Preload Audio Data to be loaded in every scene, would you?
Unfortunately, the documentation doesn’t address this in detail, making the process of deciding whether or not to Preload your audio assets very difficult and full of uncertainty.
Luckily, Unity is a sophisticated engine. After many tests, we concluded that Unity will scan everything in our scene andload all audio files flagged with Preload Audio Data that are referenced in the scene in any way.
Let’s take a step back here because now we have another question to answer:
What is a reference?
Let’s open up Unity and find out.
Testing Testing
We’ve imported 10 sound effects, 10 dialogue, and 2 music files into a Unity project. They’re all marked with Preload Audio Data to simulate a larger game. There are also two different scenes to simulate loading and unloading audio in a normal scene transition.
Let’s start with the first scene. We have a GameObject here with an AudioSource that has an AudioClip.
We hope this looks familiar.
This is already a so-called reference and this audio file will be loaded when the scene is loaded. I turned off Play on Awake for this to make sure that the audio is not played. Let’s build this and confirm with the profiler.
Our AudioClip is loaded and ready for action.
Perfect. Even though the AudioClip is not played at all, it is loaded because it has been referenced.
Note that this music file, which has “Streaming” selected as its Load Type, is only 311 bytes in the memory, unlike the 200-ish kilobytes from the last tutorial. That will change if we actually play the sound file.
Let’s now add two scripts we’ve prepared for another GameObject.
These two scripts do nothing but define a public AudioClip variable and a public AudioClip array. Let’s add an AudioClip to that and profile this.
Voilá. We have the second audio clip loaded.
For the sake of this demonstration, I will add another two AudioClips to the array and check the profiler once again.
As you might have guessed, without Preload Audio Data selected,Unity will not load the AudioClip until it is called, even though it is referenced in the scene. We’ll be going more in-depth on this in our next tutorial.
So, a reference is as simple as that. As long as you have a reference of any kind to an AudioClip, be it directly in the AudioSource, as a variable in a script, or even in a ScriptableObject, it will be loaded when the scene is loaded if you have checked Preload Audio Data.
Scene Transitions
Now: what happens if we change to another scene? Will the audio data we loaded in this scene be automatically unloaded?
Let’s go to the second scene. We’ll keep one AudioClip constant across both scenes but change the rest. Now we can build and profile this once again.
And then we’ll transition to the next scene.
We see here that all but one of our AudioClips from the first scene are already unloaded from the memory, leaving only the one that is used again in the second scene.
The unloading process took place as the scene was changed; this is a normal routine that Unity does in the background calledGarbageCollection.
Final Words
Let’s summarize what we’ve learned:
SelectingPreload Audio Datameansthe scene will not start until all sounds with this setting are loaded into memory.This ismost important for audio content that is needed right away in the scene, such as footsteps, UI, or anything synced to visual content that plays immediately upon the scene’s activation.
Unity determines which files to load in a scene by searching forreferences. If an audio file is referenced unnecessarily, for example, an AudioClip in an AudioSource that you ended up not using but didn’t delete from the scene, it will be loaded as well,even if the entire GameObject is deactivated. In that respect, it’s important to keep your scenes clear of unused references.
That’s it! We hope this tutorial has helped you to understand the Preload Audio Data option in Unity’s Import Settings and why this information is important foryour game.
If you want to learn more about how audio functions in Unity, be sure to check out our other tutorials(linked below). If you have a question, leave it in the comments or contact us directly through our website:
Unity 측에서 음원을 모노로 변환하여 용량을 줄여주는 설정 모바일이라고 ON하고 싶다.
인스펙터상이라면 이 설정을 ON으로 하면Normalize옵션 설정을 선택할 수 있게 된다. 이것은 음량을 평균화해 주는 기능입니다만, 음소재측에서 음량 조정되고 있는 케이스도 있어, 「작은 소리로 하고 싶었는데 어쨌든 음량 오르지 않았어?」같은 것이 됩니다 .
그래서, 모노럴 설정은 ON으로 하면서, 노멀라이즈는 OFF로 해 두고 싶은 기분이 되네요.
가져오기 설정을 자동화하고 싶습니다.
수동으로 하는 것은 힘들어지므로, AudioImporter 를 스크립트로부터 괴롭히고 어떻게든 하고 싶다.
그러나 AudioImpoter에는forceToMono매개 변수가 있지만 Normalize관련 매개 변수가 노출되지 않았습니다.
결과
아래와 같이 해 주면, 해당의 파라미터를 취득해 재기입할 수 있었습니다.
var audioImporter = assetImporter as AudioImporter;
var serializedObject = new UnityEditor.SerializedObject(audioImporter);
var normalize = serializedObject.FindProperty("m_Normalize");
normalize.boolValue = false;
serializedObject.ApplyModifiedProperties();
audioImporter.SaveAndReimport();
UnityEditor.EditorUtility.SetDirty(audioImporter);
UnityEditor.AssetDatabase.Refresh();
Edit > Project Settings > Audio에서DSP Buffer Size를Best latency로 설정 - Best Performance : 성능이 우선 되어 출력 시 지연이 발생할 수 있음 - Best latency : 지연이 발생하지 않는 것을 우선시하여 출력 품질이 저하될 수 있음
리소스 타입별 세팅
배경음 1 - Force To Mono : 언 체크(퀄리티에 따라 가변) - Load In Background : 체크 - Load Type : Streaming - Preload Audio Data : 언 체크 - Compression Format : Vobis (100%)
배경음 2 - Force To Mono : 언 체크(퀄리티에 따라 가변) - Load In Background : 체크 - Load Type : Compressed In Memory - Preload Audio Data : 언 체크 - Compression Format : Vobis (70%)
효과음 : 작은 크기의 빈번한 출력 - Force To Mono : 체크 - Load In Background : 언 체크 - Load Type : Decompress On Load - Preload Audio Data : 체크 - Compression Format : PCM
긴 효과음(보이스) : 중간 크기의 빈번한 출력 - Force To Mono : 체크 - Load In Background : 언 체크 - Load Type : Compressed In Memory - Preload Audio Data : 체크 - Compression Format : ADPCM
작은 크기의 가끔 발생하는 Sound - Force To Mono : 체크 - Load In Background : 언 체크 - Load Type : Compressed In Memory - Preload Audio Data : 언 체크 - Compression Format : ADPCM
중간 크기의 가끔 발생하는 Sound - Force To Mono : 체크 - Load In Background : 언체크 - Load Type : Compressed In Memory - Preload Audio Data : 언 체크 - Compression Format : Vobis (70%)
개별 리소스 세팅 정보
Force To Mono(모노 강제조정) - 스테레오를 모노로 강제 조정 - 모바일이고 최적화를 중시할 경우 설정(체크) 함
Load In Background(지연된 로딩) - 체크 시 출력 타이밍을 엄격히 지키지 않고, 느긋하게 백그라운드에서 로드 - 따라서 배경음악일 경우 사용 FX 사운드의 경우 체크 해제
Load Type - Decompress On Load 실행과 동시에 압축을 해제 작은 사이즈의 FX 사운드에 유용 많은 메모리 점유 CPU는 적게 사용
- Compressed In Memory 메모리에 압축 상태로 저장, 실행 시 압축을 해제하여 재생 약간의 성능상 오버헤드를 발생시킴 보이스 사운드 등에 사용
- Streaming 저장소에 위치한 오디오를 실시간으로 읽어냄. 보통 배경음악에서 사용
Preload Audio Data - 씬이 로딩될 때 씬에서 사용하는 모든 오디오 클립을 미리 로드 - 언체크시 플레이시 로드 하기에 랙 발생 됨
Compression Format - PCM 최고품질 / 용량 큼 / 작은 파일 크기에 적합 / FX 사운드 Load Type은 Decompress On Load로 하자 즉시 재생해야 하는 매우 짧은 효과음
- ADPCM 중간 품질 / 용량 중간 PCM대비 3.5배의 압축비, 노이즈가 포함됨 총격 소리와 같이 무압축에 가까운 품질 까지는 필요없지만, 지연시간 없이 자주 반복 재생 되야 하는 경우 적절
- Vobis 최저품질 / 용량 적음 / 배경음에 적합 압축률 설정이 가능(보통 70%로 설정) 지연 재생 되어도 무방한 일반적인 배경음