- Home /
Passing sender object as an argument in AddListener method
I'm creating Toggle elements from a prefab in a loop. While I'm creating my elements, I attach a common listener function to their onValueChanged event.
However, the listener always receive the latest object as the parameter. This is a well-known issue in Javascript but I can't solve in Unity by using "this" to pass the sender object like I do in JS.
Here's my code:
function addTenBoxes() {
for (var i = 0; i < 10; i++) {
var box = GameObject.Instantiate(myPrefab) as Toggle;
box.transform.position = Vector3(i * 100, 0, 0);
box.transform.SetParent(canvas.transform);
box.name = i.ToString();
box.onValueChanged.AddListener(function() { boxClick(box); }); // I cannot use "this" as boxClick(this); because "this" is the script object.
}
}
function boxClick(aBox : Toggle) {
Debug.Log(aBox.name); // always logs 9 which is the latest box's name
}
What is the proper way to achieve the attached event's sender object in this scenario?
Answer by Noda222 · Sep 22, 2016 at 01:46 PM
I realize you've gotten no replies at all but if you are still looking for a solution to this:
The main problem is that you are calling it from the last variable to pass through the for loop. Here's what you could do off the top of my head:
var Selected;
function addTenBoxes() {
for (var i = 0; i < 10; i++) {
var box = GameObject.Instantiate(myPrefab) as Toggle;
box.transform.position = Vector3(i * 100, 0, 0);
box.transform.SetParent(canvas.transform);
box.name = i.ToString();
box.onValueChanged.AddListener(function(b) { Selected = Box; boxClick(b); });
}
}
function boxClick(value : boolean) {
Debug.Log(Selected.name);
}
Your answer
Follow this Question
Related Questions
Event Listener for Javascript? 0 Answers
Its not playing the Audio? 2 Answers
Listener for GUIText.text change? 0 Answers
UI toggle.onValueChanged assigning method via script 1 Answer