6
2

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]for文でButtonに引数付きAddListenerするときに詰まったときの話

Posted at

最初に

uGUIのボタンで電卓的な機能を再現しようとした時に、for分でScriptからButtonのOnClickEventにAddListenerしようとした時に詰まったのでメモ

ダメコード

Calucurater.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class Calucurater : MonoBehaviour {

    /// <summary>
    /// 数字の入力を受け取る
    /// </summary>
    [SerializeField]
    private List<Button> numberBtList;

    [SerializeField]
    private InputField display;

	void Start () {

        for (int _count = 0; _count < numberBtList.Count; _count++)
        {
            numberBtList[_count].onClick.AddListener(() => OnClickNumber(_count));
        }

	}


    private void OnClickNumber(int num)
    {
        UpdateDisplay(num.ToString());
    }

    /// <summary>
    /// 結果の表示
    /// </summary>
    private void UpdateDisplay(string st)
    {
        display.text = st;
    }

	
	// Update is called once per frame
	void Update () {
		
	}
}

上記のコードだと、どのボタンを押してもループで回したインデックスの値が渡されてしまった。

動いたコード

Calucurater.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class Calucurater : MonoBehaviour {

    /// <summary>
    /// 数字の入力を受け取る
    /// </summary>
    [SerializeField]
    private List<Button> numberBtList;

    [SerializeField]
    private InputField display;

	void Start () {

        for (int _count = 0; _count < numberBtList.Count; _count++)
        {
            var i = _count;//追加

            //iを引数で渡す
            numberBtList[_count].onClick.AddListener(() => OnClickNumber(i));
        }

	}


    private void OnClickNumber(int num)
    {
        UpdateDisplay(num.ToString());
    }

    /// <summary>
    /// 結果の表示
    /// </summary>
    private void UpdateDisplay(string st)
    {
        display.text = st;
    }

	
	// Update is called once per frame
	void Update () {
		
	}
}

ループ内で一度変数に入れなおしてから引数に渡すことで期待通りの動作が確認できた。

6
2
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
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?