Sign in to follow this  

Unity How to detect if an object is the last element in an array

This topic is 3317 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I'm creating a simple object tracking system based on the Enginuity articles, primarily for learning purposes. It uses reference counting and comes with a simple garbage collector. When an object's RefCount reaches zero the objetc is considered dead and might potentially be deleted at any time. If the RefCount is above zero the object is considered alive. The garbage collector works with a dead and live list. Pretty basic. I've got everything working except for arrays. When allocating an array on the heap the address of the first element (the address obtained in an overloaded operator new[]) is added to the deadlist. It is my intention that every object in an array of tracked objects should hold the address of the first object in the array. Whenever an object in the array is alive it increases the RefCount of the first objetc in the array by one. This makes sure that the first object's RefCount (the one checked by the garbage collector) isnt zero when any of the other objects in the array are being used. I use a static variable to hold what type of object is currently being constructed. The constructor then assigns this value to a non-static member var. Since tracked objects may contain other tracked objects within themselves this static variable is actually a stack of variables. Here is my problem: When do I pop MM_HEAP_ARRAY(_TRAIL) off the stack? ie when do I know that the entire array has been constructed? My first idea was to try to retrieve x in an expression "new Object[x]" inside the overloaded operator new[]. operator new[] would then push the value onto the static stack. This would be the easiest approach but to my knowlage it isnt possible (at least without non-portable hacks). Since we do know the size of the block of memory allocted I tried to test for static_cast<byte*>(this)+sizeof(*this)==static_cast<byte*>(start_address)+mem_size This isnt good since I use a TrackedObject base class that others derive from and sizeof(*this) returns the size of the base class, not the size of the actuall object in the array. For those interested, here is another thread where I tried to tackle the problem I'm having a bit differently. It didnt work out. Thanks for any replies.

Share this post


Link to post
Share on other sites
Assuming all the array memory is contiguous, couldn't you just subtract the pointer of object 0 from the pointer to object 1 to get the size of the object? And since you know the size of the memory, the pointer to the last object should be sizeofmemory - sizeofobject.

I think new allocates everything contiguously, but I'm not 100% on my pointer arithmetic...

Share this post


Link to post
Share on other sites
That would indeed work and I have considered it. The only caveat with this approach is that it is legal (and quite possible if the number of elements to allocate is determined at runtime) for the user to allocate an array of size 1.

If the size of the array is 1 the MM_HEAP_ARRAY on top of the StaticStack would have to be poped in the first elements constructor. At that point there is no way (that I know of, this is the real problem really) to tell if there are more elements after the first.

Thanks very much for the fast response though!

PS
Quote:

I think new allocates everything contiguously, but I'm not 100% on my pointer arithmetic...

It does so pointer arithmetic is ok

Share this post


Link to post
Share on other sites
You could probably just do something like:

(T is just a template type, or whatever type the array is)


int size = 0;
T * temp = new T[2];
size = &temp[1] - &temp[0];



Every time before you build an array.

In other words just build a 2 element array of the type you want each time, then go ahead and make the ACTUAL array.

Share this post


Link to post
Share on other sites
Do you know about Boosts smart pointers?

Your design choices sound a bit awkward. You're building a reference counting system but at the same time you're complicating it with arrays of objects, where only the first object is treated as reference-counted? Why so? What do you really want to achieve here? What practical problems are you trying to solve? Why do you want to use arrays instead of stl containers?

Share this post


Link to post
Share on other sites
Thank you for the replies MortusMaximus and Captain P. Unfortunately you seem to have misunderstood the situation Im in.

I am creating an underlying tracking system, how the user wishes to create objects that uses that system is beyond my control. Therefore I have to "complicating it with arrays of objects" since I want the system to be transparent and deal with all different situations.

Also, as stated in the OP, Im doing this as a learning exercice. Therefore Boost is not an option just yet (until I expand to what will become a bigger framework).

The statement that "only the first object is treated as reference-counted" is not entirely correct. All objects are tracked with its own RefCount, the first element is special only in that it represents the entire array in the garbage collector. Since it's the first element that gets delete[]ed, and therefore is responsible for the lives of all the elements, it has to keep track of them.

On a side note, in MortusMaximus example a simple sizeof(T) would do since we know the type T of the objects we want to create. That is not the case for us since we only have controll over and can execute code in the base class.

So Im still stuck Im afraid..

EDIT - I am willing to change my design if anyone has a better idea of how to do this. The system should not impose any restrictions on how the objects can be used though.

EDIT2 - just noticed that the size var in MortusMaximus example would be 1. ie 1 object would fit between the two addresses. This is how pointer arithmetic works, as far as I know. To get the size in bytes you would have to reinterpret_cast to byte* then do the substraction.

Cheers

[Edited by - Thunder Sky on November 15, 2008 11:24:05 AM]

Share this post


Link to post
Share on other sites

This topic is 3317 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Forum Statistics

    • Total Topics
      628714
    • Total Posts
      2984357
  • Similar Content

    • By AndySv
        Total Music Collection (http://u3d.as/Pxo)   THE COLLECTION CONTAINS:   Mega Game Music Collection   Universal Music Collection   Huge library of high quality music for any project! All at an incredibly low price!   - 2,5GB of high quality audio - 100+ different music tracks - Loop and short versions   Action, fantasy, casual, horror, puzzle, epic, dramatic, romantic, positive, inspiring, motivational and more!
    • By Dafu
      FES Retro Game Framework is now available on the Unity Asset Store for your kind consideration!
      FES was born when I set out to start a retro pixel game project. I was looking around for an engine to try next. I tried a number of things, from GameMaker, to Fantasy Consoles, to MonoGame and Godot and then ended up back at Unity. Unity is just unbeatable in it's cross-platform support, and ease of deployment, but it sure as heck gets in the way of proper retro pixel games!
      So I poured over the Unity pipeline and found the lowest levels I could tie into and bring up a new retro game engine inside of Unity, but with a completely different source-code-only, classic game-loop retro blitting and bleeping API. Months of polishing and tweaking later I ended up with FES.
      Some FES features:
      Pixel perfect rendering RGB and Indexed color mode, with palette swapping support Primitive shape rendering, lines, rectangles, ellipses, pixels Multi-layered tilemaps with TMX file support Offscreen rendering Text rendering, with text alignment, overflow settings, and custom pixel font support Clipping Sound and Music APIs Simplified Input handling Wide pixel support (think Atari 2600) Post processing and transition effects, such as scanlines, screen wipes, screen shake, fade, pixelate and more Deploy to all Unity supported platforms I've put in lots of hours into a very detail documentation, you can flip through it here to get an better glimpse at the features and general overview: http://www.pixeltrollgames.com/fes/docs/index.html
      FES is carefully designed and well optimized (see live stress test demo below). Internally it uses batching, it chunks tilemaps, is careful about memory allocations, and tries to be smart about any heavy operations.
      Please have a quick look at the screenshots and live demos below and let me know what you think! I'd love to hear some opinions, feedback and questions!
      I hope I've tickled your retro feels!



      More images at: https://imgur.com/a/LFMAc
      Live demo feature reel: https://simmer.io/@Dafu/fes
      Live blitting stress test: https://simmer.io/@Dafu/fes-drawstress
      Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/102064

      View full story
    • By Dafu
      FES Retro Game Framework is now available on the Unity Asset Store for your kind consideration!
      FES was born when I set out to start a retro pixel game project. I was looking around for an engine to try next. I tried a number of things, from GameMaker, to Fantasy Consoles, to MonoGame and Godot and then ended up back at Unity. Unity is just unbeatable in it's cross-platform support, and ease of deployment, but it sure as heck gets in the way of proper retro pixel games!
      So I poured over the Unity pipeline and found the lowest levels I could tie into and bring up a new retro game engine inside of Unity, but with a completely different source-code-only, classic game-loop retro blitting and bleeping API. Months of polishing and tweaking later I ended up with FES.
      Some FES features:
      Pixel perfect rendering RGB and Indexed color mode, with palette swapping support Primitive shape rendering, lines, rectangles, ellipses, pixels Multi-layered tilemaps with TMX file support Offscreen rendering Text rendering, with text alignment, overflow settings, and custom pixel font support Clipping Sound and Music APIs Simplified Input handling Wide pixel support (think Atari 2600) Post processing and transition effects, such as scanlines, screen wipes, screen shake, fade, pixelate and more Deploy to all Unity supported platforms I've put in lots of hours into a very detail documentation, you can flip through it here to get an better glimpse at the features and general overview: http://www.pixeltrollgames.com/fes/docs/index.html
      FES is carefully designed and well optimized (see live stress test demo below). Internally it uses batching, it chunks tilemaps, is careful about memory allocations, and tries to be smart about any heavy operations.
      Please have a quick look at the screenshots and live demos below and let me know what you think! I'd love to hear some opinions, feedback and questions!
      I hope I've tickled your retro feels!



      More images at: https://imgur.com/a/LFMAc
      Live demo feature reel: https://simmer.io/@Dafu/fes
      Live blitting stress test: https://simmer.io/@Dafu/fes-drawstress
      Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/102064
    • By Dafu
      Hello all,
      I've been hard at work on a new retro pixel-perfect framework called FES Retro Game Framework. It is now available on the Unity Asset Store for your kind consideration!
      FES was born when I set out to start a retro pixel game project. I was looking around for an engine to try next. I tried a number of things, from GameMaker, to Fantasy Consoles, to MonoGame and Godot and then ended up back at Unity. Unity is just unbeatable in it's cross-platform support, and ease of deployment, but it sure as heck gets in the way of proper retro pixel games!
      So I poured over the Unity pipeline and found the lowest levels I could tie into and bring up a new retro game engine inside of Unity, but with a completely different source-code-only, classic game-loop retro blitting and bleeping API. Months of polishing and tweaking later I ended up with FES.
      Some FES features:
      Pixel perfect rendering RGB and Indexed color mode, with palette swapping support Primitive shape rendering, lines, rectangles, ellipses, pixels Multi-layered tilemaps with TMX file support Offscreen rendering Text rendering, with text alignment, overflow settings, and custom pixel font support Clipping Sound and Music APIs Simplified Input handling Wide pixel support (think Atari 2600) Post processing and transition effects, such as scanlines, screen wipes, screen shake, fade, pixelate and more Deploy to all Unity supported platforms I've put in lots of hours into a very detail documentation, you can flip through it here to get an better glimpse at the features and general overview: http://www.pixeltrollgames.com/fes/docs/index.html
      FES is carefully designed and well optimized (see live stress test demo below). Internally it uses batching, it chunks tilemaps, is careful about memory allocations, and tries to be smart about any heavy operations.
      Please have a quick look at the screenshots and live demos below and let me know what you think! I'd love to hear some opinions, feedback and questions!
      I hope I've tickled your retro feels!



      More images at: https://imgur.com/a/LFMAc
      Live demo feature reel: https://simmer.io/@Dafu/fes
      Live blitting stress test: https://simmer.io/@Dafu/fes-drawstress
      My own game I started working on using FES, a roguelike, very early: https://simmer.io/@Dafu/merl
      Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/102064
       
       
    • By Apollo Cabrera
      Yasss!!! My first Unity3d game is on the App Store and Google Play.
      Download please! About 30 minutes to get through 5 missions.
      Let me know what you guys think.
      Thanks a bunch
       
  • Popular Now