Adding listener to many objects, how to tell which one is selected

Hi,

I have a tap listener which will be added to multiple sprites, as a form of level selection.

When one is tapped how can I tell which sprite it is?

I don’t want individual listeners for each level.
Whats the best way to do this?

Thanks

local function changeLevel(event)  
 print( "level selected but which one??")  
end  
  
for i=1,12 do  
 levels[i] = display.newImage("level.png", x, y)  
 levels[i]:addEventListener("tap", changeLevel)  
end  

[import]uid: 38562 topic_id: 8596 reply_id: 308596[/import]

You could just add a tag to your objects:

levels[i].myTag = “level1” [import]uid: 13180 topic_id: 8596 reply_id: 30855[/import]

event.target [import]uid: 6645 topic_id: 8596 reply_id: 30908[/import]

thanks jmp

Was just looking through some other tutorials and seen it, and thought I could use it but can’t check until I get home.

I think because it wasn’t listed under ‘tap’ in the API I thought I couldn’t use it.

The tags from Nerderer will come in useful too :slight_smile: [import]uid: 38562 topic_id: 8596 reply_id: 30910[/import]

yes, in theory, but that specific tag will then make it awkward to access your level. try this…

[lua]local levels = {}
local x
local y

local function changeLevel(event)

local levelRef = event.target
level levelNum = levelRef.num
levels[levelNum].alpha=0.5

– or simply:
levels[event.target.num].alpha=0.5

– or even more simply :wink:
event.target.alpha = 0.5

end

for i=1,12 do
x = i * 10 – i assume you have your own code here
y = 0
levels[i] = display.newImage(“level.png”, x, y)
levels[i].num = i – we can use this later
levels[i]:addEventListener(“tap”, changeLevel)
end[/lua] [import]uid: 6645 topic_id: 8596 reply_id: 30915[/import]

(psst a small typo: “level levelNum” is supposed to be “local levelNum”) [import]uid: 12108 topic_id: 8596 reply_id: 30928[/import]

err where’s my edit button gone?! :S [import]uid: 6645 topic_id: 8596 reply_id: 30940[/import]