mirror of
https://github.com/AlexMacocian/MonoGame.Extended.git
synced 2026-07-15 15:09:29 +00:00
feat(ComponentMapper): Add 'TryGet' methods (#1006)
* feat(ComponentMapper): Add 'TryGet' methods * feat(tests): Add test for new 'TryGet' method in 'ComponentMapper' * refact(ComponentMapper): Simplify logic in 'TryGet' method
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using MonoGame.Extended.Collections;
|
||||
|
||||
namespace MonoGame.Extended.ECS
|
||||
@@ -51,6 +52,17 @@ namespace MonoGame.Extended.ECS
|
||||
return Components[entityId];
|
||||
}
|
||||
|
||||
public bool TryGet(Entity entity, [NotNullWhen(true)] out T result)
|
||||
{
|
||||
return TryGet(entity.Id, out result);
|
||||
}
|
||||
|
||||
public bool TryGet(int entityId, [NotNullWhen(true)] out T result)
|
||||
{
|
||||
result = Get(entityId);
|
||||
return result != null;
|
||||
}
|
||||
|
||||
public override bool Has(int entityId)
|
||||
{
|
||||
if (entityId >= Components.Count)
|
||||
|
||||
@@ -45,6 +45,31 @@ namespace MonoGame.Extended.ECS.Tests
|
||||
Assert.Same(component, mapper.Get(entityId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PutAndTryGetComponent()
|
||||
{
|
||||
// Arrange
|
||||
const int entityId = 4;
|
||||
const int entityIdNotAdded = 100;
|
||||
|
||||
var mapper = new ComponentMapper<Transform2>(1, _ => { });
|
||||
var component = new Transform2();
|
||||
|
||||
mapper.Put(entityId, component);
|
||||
|
||||
// Act
|
||||
bool foundAdded = mapper.TryGet(entityId, out Transform2 transformFromAdded);
|
||||
bool foundNotAdded = mapper.TryGet(entityIdNotAdded, out Transform2 transformFromNotAdded);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(typeof(Transform2), mapper.ComponentType);
|
||||
Assert.True(mapper.Components.Count >= 1);
|
||||
Assert.True(foundAdded);
|
||||
Assert.Same(component, transformFromAdded);
|
||||
Assert.False(foundNotAdded);
|
||||
Assert.Equal(default(Transform2), transformFromNotAdded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnDelete()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user