8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Unity】スクリプトからAddListenerで引数を渡す方法

Posted at

こんにちは、Unityでゲーム作ってる電車君です。
今回は、スクリプトからAddListenerで引数を渡す方法を紹介します。

なお、内容に関してはこちらに書いてあることとほぼ変わりません。
https://blog.narumium.net/2017/04/15/%E3%80%90unity%E3%80%91addlistener%E3%81%A7%E5%BC%95%E6%95%B0%E3%82%92%E6%B8%A1%E3%81%99/

using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour
{

    public GameObject buttonPrefab;

    void Start()
    {
        for (var i = 0; i < Main.onYard.transports.Count; i++)
        {
            GameObject button = Instantiate(buttonPrefab);
            var i1 = i;
            button.GetComponent<Button>().onClick.AddListener(() => TaskOnClick(i1));
        }
    }

    void TaskOnClick(int value)
    {
        print(value);
    }
}

ボタンの付け方などは説明していません。
先程のサイトと違うところは、 ii = i + 0 で変数を作成していますが、
自分の場合は、 i1 = i でやっています。

以上です。

8
4
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
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?