Created
August 29, 2024 06:32
-
-
Save antont/53e205507765eda02b5d9ca46c71f88d to your computer and use it in GitHub Desktop.
Metaplay PlayerId type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Claude Sonnet says: | |
Yes, it is possible to define entity kind specific EntityId types, such as PlayerId. | |
While the `EntityId` struct in the provided code is designed to be a general-purpose identifier for various entity types, | |
you can create wrapper types for specific entity kinds to improve type safety and readability in your code. */ | |
public readonly struct PlayerId : IEquatable<PlayerId> | |
{ | |
private readonly EntityId _entityId; | |
public PlayerId(EntityId entityId) | |
{ | |
if (!entityId.IsOfKind(EntityKindCore.Player)) | |
throw new ArgumentException("EntityId must be of kind Player", nameof(entityId)); | |
_entityId = entityId; | |
} | |
public static PlayerId Create(ulong value) | |
{ | |
return new PlayerId(EntityId.Create(EntityKindCore.Player, value)); | |
} | |
public static PlayerId FromEntityId(EntityId entityId) | |
{ | |
return new PlayerId(entityId); | |
} | |
public EntityId ToEntityId() => _entityId; | |
public static implicit operator EntityId(PlayerId playerId) => playerId._entityId; | |
public static explicit operator PlayerId(EntityId entityId) => new PlayerId(entityId); | |
public bool Equals(PlayerId other) => _entityId.Equals(other._entityId); | |
public override bool Equals(object obj) => obj is PlayerId other && Equals(other); | |
public override int GetHashCode() => _entityId.GetHashCode(); | |
public override string ToString() => _entityId.ToString(); | |
public static bool operator ==(PlayerId left, PlayerId right) => left.Equals(right); | |
public static bool operator !=(PlayerId left, PlayerId right) => !left.Equals(right); | |
} | |
/* | |
This approach provides better type safety and makes the code more self-documenting, | |
as it's clear when you're dealing with a player ID specifically rather than a generic entity ID. | |
However, it does require more upfront work to create these wrapper types and update existing code to use them. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment