RobustToolbox icon indicating copy to clipboard operation
RobustToolbox copied to clipboard

Add WeakEntityReference

Open ElectroJr opened this issue 11 months ago • 1 comments

This adds a new WeakEntityReference struct that is intended to be used by component data-fields to refer to entities that may or may not still exist, or in the case of WeakEntityReference<T> that might no longer have an otherwise required T component. Feel free to suggest better names for the struct, maybe it should just be abbreviated?.

Why

The current convention is that a a non-null EntityUid? (or NetEntity) should correspond to a valid non-deleted entity. Saving or loading entities that have components with invalid / deleted entity uids currently logs an error or completely fails, because the assumption is that you forgot to include an entity in the save or something has gone wrong. Similarly, trying to sent a deleted entityuid over the network will log an error when converting it to a NetEntity using the EntityManager helper methods.

Ensuring that entities delete or clear references to themselves when deleted or components are removed is a PITA (device linking, ghosts following, etc). So it'd be nice to have some kind of struct that points to an entity that may or may not still exist, that doesn't need to be manually cleaned up, and which yaml & network serialization knows it can just ignore if the entity is deleted or not being included in a yaml save file. Though it also shouldn't get overused, as it is obviously slower than directly using an EntityUid.

How

The struct is is just a simple wrapper around NetEntity, and there are some new IEntityManager methods & EntitySystem proxy methods to convert back to either an EntityUid? or Entity<T>? and is meant to be used with 'is' casting (i.e., if (Resolve(weakRef) is not {} ent)). Previously it used an EntityUid instead of NetEntity, but I switched mostly just to avoid having to update the auto component state generator.

ElectroJr avatar Dec 27 '24 07:12 ElectroJr

This would be very helpful for solving issues like https://github.com/space-wizards/space-station-14/issues/32642, and the more general problem of tracking projectile sources.

Tayrtahn avatar Mar 28 '25 17:03 Tayrtahn

A few suggested additions:

IEntityManager.GetWeakReference(EntityUid uid) - as a shortcut for new WeakEntityReference(EntityManager.GetNetEntity(uid))

IEntityManager.TryResolve(WeakEntityReference weakRef) - expand the suite of Resolve methods for parity with the NetEntity resolvers.

Tayrtahn avatar Jun 30 '25 16:06 Tayrtahn

Also consider adding these:

Tayrtahn avatar Jul 06 '25 16:07 Tayrtahn

IEntityManager.TryResolve(WeakEntityReference weakRef) - expand the suite of Resolve methods for parity with the NetEntity resolvers.

I've added TryGetEntity methods

Also consider adding these

I've merged all those changes i

ElectroJr avatar Jul 10 '25 07:07 ElectroJr