Page 1 of 1

How to get entity by unit_number ?

Posted: Wed Jun 17, 2020 4:09 pm
by y.petremann
So I've registered on a lot of entities and when destroyed I would like to retrieve the entity corresponding to the unit_number, here for the example I print it's name but I do more complex task.

Code: Select all

--[[ function to write
local get_entity _from_unit_number(unit_number)
	return entity
end
--]]

local function on_built_entity(e)
	script.register_on_entity_destroyed(e.created_entity)
end
Events.register{name="on_built_entity", handler=on_built_entity}

local function on_entity_destroyed(e)
	--registration_number :: uint64
	--unit_number :: uint (optional)
	local entity = get_entity _from_unit_number(e.unit_number)
	game.print(entity.name)
end
Events.register{name="on_entity_destroyed", handler=on_entity_destroyed}
I've also seen that unit_number attribute is available on entities so a mod could communicate a unit_number to another one to retrieve the entity, but how ?

Re: How to get entity by unit_number ?

Posted: Wed Jun 17, 2020 4:13 pm
by Klonan
There is no way to do it in the game API directly.

Generally you keep your own list in global with the entities indexed by their unit number

Re: How to get entity by unit_number ?

Posted: Wed Jun 17, 2020 4:21 pm
by y.petremann
Would it be possible to add a method for that because having x mods maintaining their own list of "thousands" of entities can be a little problematic ...

I think that like get_entity_by_tag we should have
LuaGameScript
get_entity_by_unit_number(unit_number) → LuaEntity

Re: How to get entity by unit_number ?

Posted: Wed Jun 17, 2020 4:35 pm
by Klonan
y.petremann wrote: Wed Jun 17, 2020 4:21 pm Would it be possible to add a method for that because having x mods maintaining their own list of "thousands" of entities can be a little problematic ...

I think that like get_entity_by_tag we should have
LuaGameScript
get_entity_by_unit_number(unit_number) → LuaEntity
There is no game engine support for that, it would just find all entities across all surfaces and compare the unit number.
Its a bad idea to add it, because then mods will use it thinking its a nice quick efficient method to get entities.

Mods storing lists of entities is fine, why do you say its problematic?
Also you generally only store entities you care about.