I am creating a ball game where I display the same ball graphic multiple times.
I had coded it as follows:
local ball1= display.newImage("redpoolball.png")
local ball2= display.newImage("redpoolball.png")
local ball3= display.newImage("redpoolball.png")
local ball4= display.newImage("redpoolball.png")
local allBallsGroup = display.newGroup()
allBallsGroup:insert( ball1 )
allBallsGroup:insert( ball2 )
allBallsGroup:insert( ball3 )
allBallsGroup:insert( ball4 )
I was just wondering if I need to load the image in 4 times or is there a more efficient solution loading it only once? [import]uid: 7863 topic_id: 2737 reply_id: 302737[/import]
if you don’t need ball1 to ball4, then do it like that:
[lua]local allBallsGroup = display.newGroup()
for i=1,4 do
local ball= display.newImage(“redpoolball.png”)
allBallsGroup:insert( ball )
end[/lua]
Other than this there is nothing that can help you creating instances from the same image. [import]uid: 5712 topic_id: 2737 reply_id: 8181[/import]
Thanks Mike
Just wanted to check I wasn’t unnecessarily loading the same image multiple times without needing to do so i.e that I didn’t just need to load it once then reuse it
i.e something like this
local allBallsGroup = display.newGroup()
local ball= display.newImage("redpoolball.png")
for i=1,4 do
allBallsGroup:insert( ball )
end
Thanks
Paul
p.s pleased to read your blog post and hear you have chosen Corona:) [import]uid: 7863 topic_id: 2737 reply_id: 8211[/import]
Yes, that’s also a way of doing it. Even shorter. [import]uid: 5712 topic_id: 2737 reply_id: 8217[/import]
Thanks Mike - does this shorter way use less resources as it only loads in the image once or is it a case of all the individual balls need to be stored in memory anyway so no real difference? [import]uid: 7863 topic_id: 2737 reply_id: 8225[/import]
Not sure the shorter version works.
I tried
local allBallsGroup = display.newGroup()
local ball= display.newImage("redpoolball.png")
allBallsGroup:insert( ball )
allBallsGroup:insert( ball )
allBallsGroup:insert( ball )
allBallsGroup:insert( ball )
print ("Number of balls = " .. allBallsGroup.numChildren)
And the result is displaying the following:
Number of balls = 1
[import]uid: 7863 topic_id: 2737 reply_id: 8235[/import]