Results 1 to 6 of 6

Thread: TList and object removing

  1. #1

    TList and object removing

    I'm going to handle collisions for sprites using TLists. One for bad guys, one for enemy bullets and one for destructible objects and one for player bullets. But I have issue with understanding how deletion of objects from TList works.

    If I want to delete object (with freeing memory), I need to do:

    Code:
    MyList.Items[4].Destroy; //let's say object we want to delete has index of 4
    MyList.Delete(4);
    right?

  2. #2
    TList does not alow direct freein of object as it serves only as colection of pointers to objects.

    If you want to automaticly free up object upon their removal from list then I suggest to use TObjectList instead.
    When TObjectList is created using
    Code:
    ObjectList := TObjectList.Create(True)
    it means that TObjectList owns the objects added to it and automatically destroys them upon removal or on destroy of the whole TObjectList.

  3. #3
    Yeah, but from what I see, it can't remove items with specific index. Which defies my purpose of having many TSprite instances and remove only specific ones.

  4. #4
    Code:
    TObject(MyList.Items[4]).Free;
    MyList.Delete(4);

  5. #5
    btw if you gonna iterate over list and remove elements in the process then better start from the end and do 'downto' or indexes will mess up

    also you might wanna check out generic collections that allow you to create TList<TSprite>
    in delphi its generics.collections unit and in lazarus fgl unit

  6. #6
    Quote Originally Posted by laggyluk View Post
    btw if you gonna iterate over list and remove elements in the process then better start from the end and do 'downto' or indexes will mess up
    Of course. I've thought that was no-brainer. Also didn't know that Freepascal has generic collections, thought it was only java/c# thing. Nice to know.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •