LoginSignup
11
11

More than 5 years have passed since last update.

Unity2d 別のGameObjectにメッセージを送る(SendMessage)

Posted at

概要

例えば、アクション等で、プレイヤーキャラがダメージを受けた場合、

ゲーム全体を管理しているマネージャーにその情報を送りたいという事は往々にしてあります。

その時に情報を送るやり方の1つとして、SendMessageと言う機能があります。

(iOSで言うところの、Notificationが近しいかも)

やり方

オブジェクトAから、オブジェクトBにメッセージを送る例

// オブジェクトAの処理
GameObject objectB = GameObject.FindGameObjectsWithTag ("ObjectB");
objectB.SendMessage("hogehogeMessage");
// オブジェクトBの処理
void hogehogeMessage() {
    /* 処理 */
} 

上記の用に記述することによって、オブジェクトAの然るべきタイミングで、オブジェクトBのhogehogeMessageメソッドをコールすることが出来ます。

また、引数を持たせたい場合は以下のように記述します。

// オブジェクトAの処理
GameObject objectB = GameObject.FindGameObjectsWithTag ("ObjectB");
objectB.SendMessage("hogehogeMessage", 10);
// オブジェクトBの処理
void hogehogeMessage(int arg) {
    /* 処理 */
} 

その他にも、SendMessageは単純にメッセージを送る機能ですから、同時にいくつも送信しても問題ありません。

// オブジェクトAの処理
GameObject[] objectBArray = GameObject.FindGameObjectsWithTag ("ObjectB");
foreach (var obj in objectBArray) {
    obj.SendMessage("hogehogeMessage");
}
// オブジェクトBの処理
void hogehogeMessage() {
    /* 処理 */
} 
11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11