Remove an object from a list
BlitzMax Forums/BlitzMax Beginners Area/Remove an object from a list
| ||
Hello community, I'm trying to remove an object from my screen which I believe I should be doing by removing it from the list within which it is stored. It is doing my head in and hope that perhaps someone can educate me about my failings. I get a "chicken and egg" scenario as it seems that I want to add some code to remove a "player" object that has yet to be created. Thanks in advance, and I have highlighted the line which I am having trouble with below: SuperStrict SeedRnd MilliSecs() Type TEntity Global EntityList:TList = New TList Field x:Float, y:Float Method Draw() Abstract Method New() EntityList.AddLast(Self) End Method Method Remove() EntityList.Remove(Self) End Method Function DrawAll() Local ent:TEntity For ent = EachIn EntityList ent.Draw() Next End Function End Type Type TPlayer Extends TEntity Field d:Int Field R:Int, G:Int, B:Int Method Draw() SetColor R, G, B DrawOval x, y, d, d End Method End Type 'gameloop********************************************** Graphics 640, 480 While Not KeyDown(key_escape) Cls If MouseHit(1) Then Local player:TPlayer = New TPlayer player.x = Rnd(640); player.y = Rnd(480) player.d = Rnd(100) player.R = Rnd(255) player.G = Rnd(255) player.B = Rnd(255) EndIf If MouseHit(2) Then player.Remove() '<-------- BMax is somewhat unamused by this line EndIf 'Draw all entities TEntity.DrawAll() Flip Wend |
| ||
That is because you are defining player as local within the If/Endif block. It looses scope after the Endif and is no longer available for the rest of the code. In order for it to work, you need to move the declaration outside the block.SuperStrict SeedRnd MilliSecs() Type TEntity Global EntityList:TList = New TList Field x:Float, y:Float Method Draw() Abstract Method New() EntityList.AddLast(Self) End Method Method Remove() EntityList.Remove(Self) End Method Function DrawAll() Local ent:TEntity For ent = EachIn EntityList ent.Draw() Next End Function End Type Type TPlayer Extends TEntity Field d:Int Field R:Int, G:Int, B:Int Method Draw() SetColor R, G, B DrawOval x, y, d, d End Method End Type 'gameloop********************************************** Graphics 640, 480 Local player:TPlayer '<---Move this to here. While Not KeyDown(key_escape) Cls If MouseHit(1) Then player = New TPlayer player.x = Rnd(640); player.y = Rnd(480) player.d = Rnd(100) player.R = Rnd(255) player.G = Rnd(255) player.B = Rnd(255) EndIf If MouseHit(2) Then player.Remove() '<-------- BMax is somewhat unamused by this line EndIf 'Draw all entities TEntity.DrawAll() Flip Wend |
| ||
Thanks TomToad, I spent excessive time banging my head against my desk on this but as soon as you point it out it seems obvious! Thanks again, George |