Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
いまさらだけど確認しておこう Coroutine
Search
RyotaMurohoshi
September 15, 2018
Technology
4
7.9k
いまさらだけど確認しておこう Coroutine
2019/09/15に開催された「Unity非同期完全に理解した」勉強会のLT資料です。
https://connpass.com/event/95696/
RyotaMurohoshi
September 15, 2018
Tweet
Share
More Decks by RyotaMurohoshi
See All by RyotaMurohoshi
Unityの合同同人誌や合同商業誌を書いてる僕は感想やレビューや評価が欲しい
ryotamurohoshi
0
490
Unity 2021.1での Unityパッケージの名称変更について
ryotamurohoshi
0
670
Odin Validationはいいぞ!
ryotamurohoshi
2
910
Tilemapはいいぞ!2020 〜すごいぞ、プロジェクト専用拡張Brush〜
ryotamurohoshi
0
2.3k
Unityでも、新しいC#
ryotamurohoshi
0
1.3k
Riderはいいぞ!
ryotamurohoshi
1
3.4k
Riderのススメ〜俺はRiderここが好き〜
ryotamurohoshi
1
2.3k
Unity開発者に伝えたい.NETのこと
ryotamurohoshi
4
37k
ImportedLinqのススメ
ryotamurohoshi
0
1.3k
Other Decks in Technology
See All in Technology
20250304_赤煉瓦倉庫_DeepSeek_Deep_Dive
hiouchiy
2
120
役員・マネージャー・著者・エンジニアそれぞれの立場から見たAWS認定資格
nrinetcom
PRO
4
6.5k
EMConf JP 2025 懇親会LT / EMConf JP 2025 social gathering
sugamasao
2
210
AIエージェント開発のノウハウと課題
pharma_x_tech
8
4.5k
JAWS FESTA 2024「バスロケ」GPS×サーバーレスの開発と運用の舞台裏/jawsfesta2024-bus-gps-serverless
ma2shita
3
290
LINEギフトにおけるバックエンド開発
lycorptech_jp
PRO
0
400
AIエージェント元年@日本生成AIユーザ会
shukob
1
250
IAMのマニアックな話2025
nrinetcom
PRO
6
1.4k
2/18 Making Security Scale: メルカリが考えるセキュリティ戦略 - Coincheck x LayerX x Mercari
jsonf
0
240
Охота на косуль у древних
ashapiro
0
120
ディスプレイ広告(Yahoo!広告・LINE広告)におけるバックエンド開発
lycorptech_jp
PRO
0
520
マーケットプレイス版Oracle WebCenter Content For OCI
oracle4engineer
PRO
3
540
Featured
See All Featured
A better future with KSS
kneath
238
17k
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
30
2.2k
Designing Experiences People Love
moore
140
23k
Large-scale JavaScript Application Architecture
addyosmani
511
110k
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
193
16k
YesSQL, Process and Tooling at Scale
rocio
172
14k
Building Better People: How to give real-time feedback that sticks.
wjessup
367
19k
RailsConf 2023
tenderlove
29
1k
The Language of Interfaces
destraynor
156
24k
Building a Modern Day E-commerce SEO Strategy
aleyda
38
7.1k
The Myth of the Modular Monolith - Day 2 Keynote - Rails World 2024
eileencodes
21
2.5k
Stop Working from a Prison Cell
hatefulcrawdad
268
20k
Transcript
いまさらだけど確認しておこう Coroutine @RyotaMurohoshi 2018/09/15(土) Unity非同期完全に理解した勉強会
2015年3月21日
None
いやぁ~~っ! 未来、ついに来ましたね!
async/await、最高ですね! ガンガン使っていきましょう!
ところでちょっと 現実に、そして日常に戻りましょう
Unityのバージョン何ですか? 2018系?2017系?5系?もしかして4系?
『最新作を作っているバージョン』だけじゃないですよ! 『利益を生み出しているゲームのバージョン』は何ですか!?
世の中のすべてのUnityプロジェクトが (特になんの工夫もせず) async/awaitが使えるわけじゃない・・・ 使えるけれど、大人のあれで使わないってこともあるよね
ある程度利益を出していて大きく変更予定のないヤツ 大人の事情でUnityをアップデートできないヤツ こういうプロジェクト、まれによくある
世の中の全てのUnityプロジェクトで async/awaitが使えるわけじゃない・・・
というわけで・・・
いまさらだけど確認しておこう Coroutine @RyotaMurohoshi 2018/09/15(土) Unity非同期完全に理解した勉強会
※ 私の勤め先や個人ではUnity 2018やasync/await 使えますよ!
Coroutineがasync/awaitの代わりになるわけじゃない async/awaitが使える場所ではそっち使おう! Rxが適切な時もあるよ!
けれど、それでも・・・
古いプロジェクトをメンテ・改善していると Coroutineが助けてくれること、ある! Coroutineのデバックで嵌ることも、あるかも! 今更だけど、このタイミングで確認しておきましょう!
基本的なCoroutineの使い方は 知っている前提で いくつか(みんなが知っているかもしれないけど)Tipsを話します
public void StartLaunchLoop() { StartCoroutine(LaunchCoroutine()); } private IEnumerator LaunchCoroutine() {
// 1秒に一回 Launch が呼び出される while (true) { Launch(); yield return new WaitForSeconds(1.0F); } } private void Launch() { // 略 }
「当たり前」って大切 確認していきましょう
その1
void Start() { // 入れ子のコルーチンを呼び出す StartCoroutine(ParentRoutine()); } IEnumerator ParentRoutine() {
Debug.Log("start parent"); // 子コルーチンの呼び出し yield return ChildRoutine(); Debug.Log("end parent"); } IEnumerator ChildRoutine() { Debug.Log("start child"); yield return new WaitForSeconds(1.0F); Debug.Log("end child"); } 実行結果 start parent start child end child end parent ※ Unity 5.3 以降
その1 Coroutineの入れ子でStartCoroutineがいらないのはUnity 5.3から! Unity 5.2とそれより前ではStartCoroutineが必要! コンパイルエラーにならないからこそ、気を付けよう!
void Start() { // 入れ子のコルーチンを呼び出す StartCoroutine(ParentRoutine()); } IEnumerator ParentRoutine() {
Debug.Log("start parent"); // 子コルーチンの呼び出し yield return ChildRoutine(); Debug.Log("end parent"); } IEnumerator ChildRoutine() { Debug.Log("start child"); yield return new WaitForSeconds(1.0F); Debug.Log("end child"); } 実行結果 Unity 5.3 以降 start parent start child end child end parent 実行結果 Unity 5.2 以前 start parent end parent
void Start() { // 入れ子のコルーチンを呼び出す StartCoroutine(ParentRoutine()); } IEnumerator ParentRoutine() {
Debug.Log("start parent"); // Unity 5.2以前で子コルーチンの呼び出し // StartCoroutineが必要! yield return StartCoroutine(ChildRoutine()); Debug.Log("end parent"); } IEnumerator ChildRoutine() { Debug.Log("start child"); yield return new WaitForSeconds(1.0F); Debug.Log("end child"); } 実行結果 start parent start child end child end parent
コンパイルエラーにならないからこそたちが悪い! Unity 5.3以上になれている人が、古いプロジェクトを触って これに気が付かず、コンパイルは通るのに 「あれ、なんか思ってる挙動と違う!?」ってなるorz
その2
その2 WaitForSecondsはTime.timeScaleの影響を受ける 影響を受けたくないならば、WaitForSecondsRealtimeを使う! 注) WaitForSecondsRealtimeはUnity 5.3から利用可能
IEnumerator WaitRoutine() { Debug.Log("start"); // ↓Time.timescaleの影響を受ける yield return new WaitForSeconds(1.0F);
// ↓Time.timescaleの影響を受けない yield return new WaitForSecondsRealtime(1.0F); Debug.Log("end"); }
その3
その3 Unity 5.3からはWaitUntil、WaitWhile、 そしてCustomYieldInstructionを活用しよう!
IEnumerator BattleRoutine() { SetUiBeforeBattle(); yield return new WaitUntil(() => onReadyBattle);
// onReadyBattleがtrueになったらここに到達 StartBattle(); // 略 }
CustomYieldInstructionを使えば、 自分でWaitUntil・WaitWhileみたいなクラスを 柔軟に作れる
その4
その4 Unity 5.2とそれより古いバージョンでも WaitUntil、WaitWhile、CustomYieldInstructionは作れる・使える ただしStartCoroutineとの併用が必要!
WaitUntil、WaitWhile、CustomYieldInstructionは Unity 5.3から導入された型。けどUnity 5.2以前でも自分で作れる。
public abstract class CustomYieldInstruction : IEnumerator { public abstract bool
keepWaiting { get; } public object Current { get { return null; } } public bool MoveNext() { return keepWaiting; } public void Reset() { } } public sealed class WaitUntil : CustomYieldInstruction { Func<bool> m_Predicate; public override bool keepWaiting { get { return !m_Predicate(); } } public WaitUntil(Func<bool> predicate) { m_Predicate = predicate; } }
IEnumerator BattleRoutine() { SetUiBeforeBattle(); // StartCoroutineが必要なことに注意! yield return new StartCoroutine(WaitUntil(()
=> onReadyBattle)); // onReadyBattleがtrueになったらここに到達 StartBattle(); // 略 }
その5
その5 StopCoroutine(Coroutine routine)が使えるのは、 Unity 2017.1から!
その6
その6 StartCoroutineしたコンポーネントがdisableになっても Coroutineは動き続ける
その7
その7 StartCoroutineしたコンポーネントが破壊されると Coroutineは止まる
その8
その8 StartCoroutineしたコンポーネントを 持つGameObjectが破壊されるとCoroutineは止まる
その9
その9 StartCoroutineしたコンポーネントを 持つGameObjectがSetActivate(false) されると Coroutineは止まる。再開もしない。
「あれ何でCoroutine動かないの?」って思ったら、 コンポーネントが破壊されてないかも確認しましょう
その10
その10 StartCoroutine(IEnumerator)したCoroutineは、 StopCoroutine(string)じゃ止められない。
void Start() { StartCoroutine(SpawnRoutine()); } void StopSpawn() { // StartCoroutine(IEnumerator)で始めたCoroutineは、
// StopCoroutine(string)では止められない StopCoroutine("SpawnRoutine"); } IEnumerator SpawnRoutine() { // 略 }
その11
その11 あるコンポーネントにおいて StartCoroutine(string)したCoroutineが複数あって、 StopCoroutine(string) すると そのstring(メソッド名)のすべてのCoroutineが止まる
void Start() { // Coroutineは複数走っている StartCoroutine("SpawnRoutine"); StartCoroutine("SpawnRoutine"); } void StopSpawn()
{ // このコンポーネントのSpawnRoutine(文字列)がすべて止まる StopCoroutine("SpawnRoutine"); } IEnumerator SpawnRoutine() { // 略 }
※ 文字列でのStartCoroutine・StopCoroutineの利用 おすすめしません
その12
その12 StopAllCoroutinesはそのコンポーネントがStartした Coroutineをすべて止める StartCoroutine(string)・StartCoroutine(IEnumerator)で始めたやつどちらもすべて。
その13
その13 StartやOnCollisionEnterなどのイベント関数も Coroutineライクに書ける
void OnCollisionEnter(Collision collision) { Debug.Log(collision.gameObject.name); // すぐに殺す Destroy(collision.gameObject); }
// voidじゃなくて、IEnumerator IEnumerator OnCollisionEnter(Collision collision) { Debug.Log(collision.gameObject.name); // 1秒待ってから殺す yield
return new WaitForSeconds(1.0F); Destroy(collision.gameObject); }
その14
その14 Coroutineはコンポーネントのインスタンスに紐づく
その15
その15 Coroutineはメインスレッドで動く
まとめ
Coroutineがasync/awaitの代わりになるわけじゃない async/awaitが使える場所ではそっち使おう! Rxが適切な時もあるよ!
けれど、それでも・・・
古いプロジェクトをメンテ・改善していると Coroutineが助けてくれること、ある! Coroutineのデバックで嵌ることも、あるかも! 今更だけど、このタイミングで確認、大切ですね!
async / awaitはいいぞ! Rxもいいぞ! Coroutineもプロジェクトによっては、使う時があるよね!
いまさらだけど確認しておこう Coroutine @RyotaMurohoshi 2018/09/15(土) Unity非同期完全に理解した勉強会