More than 5 years have passed since last update.
はじめての非同期処理 call backは,送信機と受信機のイメージで.(OcuGo.Games)
1
Last updated at Posted at 2019-02-03
1. 非同期処理とは。
このボタンが押されたら、とか。
敵が3体倒されたら、とか。
一般論でいうと、この人から電話がきたら、とか。
自分のタイミングではなく、外部からのトリガーで処理を実行したい際に「非同期処理」を使います。
2. 送り手と受け手がいる.
送り手: 条件を満たしました!
👁 keitai_mukashi.png
受け手: 条件満たしたのね.連絡ありがと! 次の処理流そっと.
👁 denwa_business_woman.png
3. callbackは System.Action型
C#では、System.Action型の Callback という関数が用意されています.
以下では、「スペースキーが3回押されたら」という条件をトリガーに、次の処理を流すという設定でコードを紹介します。
送り手側
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CountSpace : MonoBehaviour {
System.Action Callback;
int spacenum = 0;
// Update is called once per frame
void Update()
{ //スペースキーを押すとspacenumをカウントアップする.
if (Input.GetKeyDown(KeyCode.Space)){
this.spacenum++;
}
//スペースキーが3回押されたら
if (spacenum == 3) {
this.Callback(); //送信機を使用して連絡をする.
}
}
//送信機の設置
public void SetCallback(System.Action Callback)
{
this.Callback = Callback; //
}
受け手側
public CountSpace A; //CountSpaceという classの Aという変数
// Use this for initialization
void Start ()
{ //電話が来たらカッコ内の処理を流す.
A.SetCallback(連絡を受け取ってから流したい処理);
}
ここでは仮に変数名をAとしましたが,なんでも構いません.
イメージ的にはAさんからかかってきたらということですが,そのAさんが誰であるか限定する必要がないためです。
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
