Replace Lazy trait lookups with INotifyCreated.

This commit is contained in:
Paul Chote
2017-05-28 14:25:11 +01:00
committed by atlimit8
parent 69587a2128
commit 34844e87a3
6 changed files with 33 additions and 22 deletions

View File

@@ -39,7 +39,7 @@ namespace OpenRA.Mods.Common.Traits
public override abstract object Create(ActorInitializer init);
}
public abstract class AttackBase : ConditionalTrait<AttackBaseInfo>, IIssueOrder, IResolveOrder, IOrderVoice, ISync
public abstract class AttackBase : ConditionalTrait<AttackBaseInfo>, INotifyCreated, IIssueOrder, IResolveOrder, IOrderVoice, ISync
{
readonly string attackOrderName = "Attack";
readonly string forceAttackOrderName = "ForceAttack";
@@ -47,9 +47,9 @@ namespace OpenRA.Mods.Common.Traits
[Sync] public bool IsAttacking { get; internal set; }
public IEnumerable<Armament> Armaments { get { return getArmaments(); } }
protected Lazy<IFacing> facing;
protected Lazy<Building> building;
protected Lazy<IPositionable> positionable;
protected IFacing facing;
protected Building building;
protected IPositionable positionable;
protected Func<IEnumerable<Armament>> getArmaments;
readonly Actor self;
@@ -58,15 +58,23 @@ namespace OpenRA.Mods.Common.Traits
: base(info)
{
this.self = self;
}
var armaments = Exts.Lazy(() => self.TraitsImplementing<Armament>()
.Where(a => info.Armaments.Contains(a.Info.Name)).ToArray());
void INotifyCreated.Created(Actor self)
{
facing = self.TraitOrDefault<IFacing>();
building = self.TraitOrDefault<Building>();
positionable = self.TraitOrDefault<IPositionable>();
getArmaments = () => armaments.Value;
getArmaments = InitializeGetArmaments(self);
}
facing = Exts.Lazy(() => self.TraitOrDefault<IFacing>());
building = Exts.Lazy(() => self.TraitOrDefault<Building>());
positionable = Exts.Lazy(() => self.Trait<IPositionable>());
protected virtual Func<IEnumerable<Armament>> InitializeGetArmaments(Actor self)
{
var armaments = self.TraitsImplementing<Armament>()
.Where(a => Info.Armaments.Contains(a.Info.Name)).ToArray();
return () => armaments;
}
protected virtual bool CanAttack(Actor self, Target target)
@@ -85,7 +93,7 @@ namespace OpenRA.Mods.Common.Traits
return false;
// Building is under construction or is being sold
if (building.Value != null && !building.Value.BuildComplete)
if (building != null && !building.BuildComplete)
return false;
if (Armaments.All(a => a.IsReloading))
@@ -100,7 +108,7 @@ namespace OpenRA.Mods.Common.Traits
return;
foreach (var a in armaments ?? Armaments)
a.CheckFire(self, facing.Value, target);
a.CheckFire(self, facing, target);
}
public IEnumerable<IOrderTargeter> Orders
@@ -188,7 +196,7 @@ namespace OpenRA.Mods.Common.Traits
if (IsTraitDisabled)
return false;
if (Info.AttackRequiresEnteringCell && !positionable.Value.CanEnterCell(t.Actor.Location, null, false))
if (Info.AttackRequiresEnteringCell && (positionable == null || !positionable.CanEnterCell(t.Actor.Location, null, false)))
return false;
// PERF: Avoid LINQ.