dk3611
dk3611

Reputation: 51

How to access the object names when they are created randomly

Random objects are created on the screen with the help of code written below. I want to give these random objects name and access it when user taps a particular object, i am actually creating a game when user taps on a particular objects, then only that particular object must shoot. Please give any suggestion thanks...

imageHolder = {} 
numOfImages = 10 

for i=1,numOfImages do 
   imageHolder[i] = display.newImageRect("myImage.png", 20, 20)
   imageHolder[i].name="images"
   imageHolder[i].x = math.random(0, display.contentWidth) 
   imageHolder[i].y = math.random(0, display.contentHeight) 
end

Upvotes: 0

Views: 146

Answers (1)

DevfaR
DevfaR

Reputation: 1616

you can achieve it by giving each object a unique ID you can refer to my code and if you tap every square it will print the ID you assign to them

imageHolder = {} 
numOfImages = 10 

local function onTap(event)

    local t = event.target
    -- t.name is the name you assign to the object
    print(t.name)

end


for i=1,numOfImages do 
   imageHolder[i] = display.newRect(0,0, 20, 20)
   imageHolder[i].name="images "..i
   imageHolder[i].x = math.random(0, display.contentWidth) 
   imageHolder[i].y = math.random(0, display.contentHeight) 
   imageHolder[i]:addEventListener("tap", onTap)
end

Upvotes: 4

Related Questions