Possible for instances of a class to count themselves, without need for a watcher?

Say you have a bunch of Cube actors in the level.

At either runtime or maybe the construction script, you want to count up how many there are and assign each a number (this way they can be numbered 1,2,3, etc. It’s for display purposes)

Is it possible to do this without some other class looking at them and counting?

If I have each instance of the Cube actor say, “on construct or on begin play, get all actors of my class” thats no good.

In C++ you can use a static member that you increment in the constructor, and perhaps decrement in the destructor (depending on whether you want a serial number, or a currently live count.)

Beware, though, that the engine will create extra instances of your object for the Class Default Object, as well as to use when serializing levels and savegames.

In blueprint only, you don’t quite have the constructor/destructor access that you have in C++, so you may have to “Add C++ Class” that subclasses AActor, and then subclass your Cube from that for this to work.

2 Likes

thanks @jwatte

I had to lookup static member in the microsoft c++ docs but the idea seems simple enough. Sort of like attaching a global variable that is loosely tied to the class but is not exactly a member of that class.

Seems like the perfect use case. I’ll give a try with it, but given my noobishness with c++, if it looks like it will take me all day, I may just do a simper blueprint only workaround like this:
spawn an actor whose sole responsibility is to do the counting, it reports back the count and the counted actors can set their display numbers, then destroy the counter.

I mean that sounds kinda stupid but it only takes me 10 minutes to setup and I know it can work.

But maybe I can get the c++ working without too much headache then I can feel like a legit programmer :slight_smile:

heres something of interest:
Static class members for Blueprints [Unreal] – Dario Mazzanti

looks like same idea as mentioned above, just step by step