Use Null-Propagation Operator

This commit is contained in:
teinarss
2020-08-16 11:38:14 +02:00
committed by Paul Chote
parent 8d27d22100
commit 9c4fd0e3d3
113 changed files with 219 additions and 464 deletions

View File

@@ -128,8 +128,8 @@ namespace OpenRA.Mods.Common.Activities
return true;
// AbortOnResupply cancels the current activity (after resupplying) plus any queued activities
if (attackAircraft.Info.AbortOnResupply && NextActivity != null)
NextActivity.Cancel(self);
if (attackAircraft.Info.AbortOnResupply)
NextActivity?.Cancel(self);
QueueChild(new ReturnToBase(self));
returnToBase = true;

View File

@@ -112,11 +112,7 @@ namespace OpenRA.Mods.Common.Activities
t.OnCapture(enterActor, self, oldOwner, self.Owner, captures.Info.CaptureTypes);
if (self.Owner.Stances[oldOwner].HasStance(captures.Info.PlayerExperienceStances))
{
var exp = self.Owner.PlayerActor.TraitOrDefault<PlayerExperience>();
if (exp != null)
exp.GiveExperience(captures.Info.PlayerExperience);
}
self.Owner.PlayerActor.TraitOrDefault<PlayerExperience>()?.GiveExperience(captures.Info.PlayerExperience);
if (captures.Info.ConsumedByCapture)
self.Dispose();

View File

@@ -177,8 +177,7 @@ namespace OpenRA.Mods.Common.Activities
if (IsCanceling && mobile.CanStayInCell(mobile.ToCell))
{
if (path != null)
path.Clear();
path?.Clear();
return true;
}

View File

@@ -138,9 +138,7 @@ namespace OpenRA.Mods.Common.Activities
QueueChild(move.MoveTo(targetCell, targetLineColor: Color.Green));
var delta = (self.CenterPosition - host.CenterPosition).LengthSquared;
var transport = transportCallers.FirstOrDefault(t => t.MinimumDistance.LengthSquared < delta);
if (transport != null)
transport.RequestTransport(self, targetCell);
transportCallers.FirstOrDefault(t => t.MinimumDistance.LengthSquared < delta)?.RequestTransport(self, targetCell);
return false;
}
@@ -261,11 +259,7 @@ namespace OpenRA.Mods.Common.Activities
if (health.DamageState == DamageState.Undamaged)
{
if (host.Actor.Owner != self.Owner)
{
var exp = host.Actor.Owner.PlayerActor.TraitOrDefault<PlayerExperience>();
if (exp != null)
exp.GiveExperience(repairsUnits.Info.PlayerExperience);
}
host.Actor.Owner.PlayerActor.TraitOrDefault<PlayerExperience>()?.GiveExperience(repairsUnits.Info.PlayerExperience);
Game.Sound.PlayNotification(self.World.Map.Rules, self.Owner, "Speech", repairsUnits.Info.FinishRepairingNotification, self.Owner.Faction.InternalName);

View File

@@ -60,8 +60,7 @@ namespace OpenRA.Mods.Common
askedColor.ToAhsv(out _, out _, out var s, out var v);
if (s < HsvSaturationRange[0] || s > HsvSaturationRange[1] || v < HsvValueRange[0] || v > HsvValueRange[1])
{
if (errorMessages != null)
errorMessages.Add("Color was adjusted to be inside the allowed range.");
errorMessages?.Add("Color was adjusted to be inside the allowed range.");
forbiddenColor = askedColor;
return false;
}
@@ -69,16 +68,14 @@ namespace OpenRA.Mods.Common
// Validate color against the current map tileset
if (!IsValid(askedColor, terrainColors, out forbiddenColor))
{
if (errorMessages != null)
errorMessages.Add("Color was adjusted to be less similar to the terrain.");
errorMessages?.Add("Color was adjusted to be less similar to the terrain.");
return false;
}
// Validate color against other clients
if (!IsValid(askedColor, playerColors, out forbiddenColor))
{
if (errorMessages != null)
errorMessages.Add("Color was adjusted to be less similar to another player.");
errorMessages?.Add("Color was adjusted to be less similar to another player.");
return false;
}

View File

@@ -178,37 +178,27 @@ namespace OpenRA.Mods.Common
public static void UpdateStatus(DiscordState state, string details = null, string secret = null, int? players = null, int? slots = null)
{
var service = GetService();
if (service != null)
service.SetStatus(state, details, secret, players, slots);
GetService()?.SetStatus(state, details, secret, players, slots);
}
public static void SetPlayers(int players, int slots)
{
var service = GetService();
if (service != null)
GetService()?.client.UpdateParty(new Party
{
service.client.UpdateParty(new Party
{
ID = Secrets.CreateFriendlySecret(new Random()),
Size = players,
Max = slots
});
}
ID = Secrets.CreateFriendlySecret(new Random()),
Size = players,
Max = slots
});
}
public static void UpdatePlayers(int players, int slots)
{
var service = GetService();
if (service != null)
service.client.UpdatePartySize(players, slots);
GetService()?.client.UpdatePartySize(players, slots);
}
public static void UpdateDetails(string details)
{
var service = GetService();
if (service != null)
service.client.UpdateDetails(details);
GetService()?.client.UpdateDetails(details);
}
}
}

View File

@@ -96,17 +96,10 @@ namespace OpenRA.Mods.Common.Effects
arrowSpeed *= -1;
}
if (arrow != null)
arrow.Tick();
if (beacon != null)
beacon.Tick();
if (circles != null)
circles.Tick();
if (clock != null)
clock.Tick();
arrow?.Tick();
beacon?.Tick();
circles?.Tick();
clock?.Tick();
if (duration > 0 && duration <= tick++)
owner.World.AddFrameEndTask(w => w.Remove(this));

View File

@@ -48,18 +48,15 @@ namespace OpenRA.Mods.Common.Effects
void IEffect.Tick(World world)
{
if (flag != null)
flag.Tick();
flag?.Tick();
if (circles != null)
circles.Tick();
circles?.Tick();
if (cachedLocations == null || !cachedLocations.SequenceEqual(rp.Path))
{
UpdateTargetLineNodes(world);
if (circles != null)
circles.Play(rp.Info.CirclesSequence);
circles?.Play(rp.Info.CirclesSequence);
}
if (!building.IsInWorld || building.IsDead)

View File

@@ -107,8 +107,7 @@ namespace OpenRA.Mods.Common.FileFormats
for (var i = 0; i < next; i++)
output.WriteByte(outBuffer[i]);
if (onProgress != null)
onProgress(input.Position - inputStart, output.Position - outputStart);
onProgress?.Invoke(input.Position - inputStart, output.Position - outputStart);
break;
}
@@ -155,8 +154,7 @@ namespace OpenRA.Mods.Common.FileFormats
next = 0;
first = false;
if (onProgress != null)
onProgress(input.Position - inputStart, output.Position - outputStart);
onProgress?.Invoke(input.Position - inputStart, output.Position - outputStart);
}
}
while (len != 0);
@@ -173,8 +171,7 @@ namespace OpenRA.Mods.Common.FileFormats
next = 0;
first = false;
if (onProgress != null)
onProgress(input.Position - inputStart, output.Position - outputStart);
onProgress?.Invoke(input.Position - inputStart, output.Position - outputStart);
}
}
}

View File

@@ -243,8 +243,7 @@ namespace OpenRA.Mods.Common.FileFormats
toExtract -= bytesToExtract;
while (!inf.IsNeedingInput)
{
if (onProgress != null)
onProgress((int)(100 * output.Position / file.ExpandedSize));
onProgress?.Invoke((int)(100 * output.Position / file.ExpandedSize));
var inflated = inf.Inflate(buffer);
output.Write(buffer, 0, inflated);
@@ -258,8 +257,7 @@ namespace OpenRA.Mods.Common.FileFormats
{
do
{
if (onProgress != null)
onProgress((int)(100 * output.Position / file.ExpandedSize));
onProgress?.Invoke((int)(100 * output.Position / file.ExpandedSize));
toExtract -= remainingInArchive;
output.Write(GetBytes(remainingInArchive), 0, (int)remainingInArchive);

View File

@@ -101,8 +101,7 @@ namespace OpenRA.Mods.Common.FileFormats
var decompressedBytes = 0;
for (var i = 0; i < folder.BlockCount; i++)
{
if (onProgress != null)
onProgress((int)(100 * output.Position / file.DecompressedLength));
onProgress?.Invoke((int)(100 * output.Position / file.DecompressedLength));
// Ignore checksums
stream.Position += 4;

View File

@@ -52,8 +52,7 @@ namespace OpenRA.Mods.Common.LoadScreens
dpiScale = scale;
// Force images to be reloaded on the next display
if (sheet != null)
sheet.Dispose();
sheet?.Dispose();
sheet = null;
}
@@ -94,8 +93,8 @@ namespace OpenRA.Mods.Common.LoadScreens
protected override void Dispose(bool disposing)
{
if (disposing && sheet != null)
sheet.Dispose();
if (disposing)
sheet?.Dispose();
base.Dispose(disposing);
}

View File

@@ -218,8 +218,7 @@ namespace OpenRA.Mods.Common.Orders
world.CancelInputMode();
foreach (var v in variants)
if (v.Preview != null)
v.Preview.Tick();
v.Preview?.Tick();
}
void IOrderGenerator.SelectionChanged(World world, IEnumerable<Actor> selected) { }

View File

@@ -197,8 +197,7 @@ namespace OpenRA.Mods.Common.Projectiles
public void Tick(World world)
{
if (anim != null)
anim.Tick();
anim?.Tick();
lastPos = pos;
pos = WPos.LerpQuadratic(source, target, angle, ticks, length);

View File

@@ -100,8 +100,7 @@ namespace OpenRA.Mods.Common.Projectiles
args.Weapon.Impact(Target.FromPos(pos), warheadArgs);
}
if (anim != null)
anim.Tick();
anim?.Tick();
}
public IEnumerable<IRenderable> Render(WorldRenderer wr)

View File

@@ -792,8 +792,7 @@ namespace OpenRA.Mods.Common.Projectiles
public void Tick(World world)
{
ticks++;
if (anim != null)
anim.Tick();
anim?.Tick();
// Switch from freefall mode to homing mode
if (ticks == info.HomingActivationDelay + 1)

View File

@@ -227,8 +227,7 @@ namespace OpenRA.Mods.Common.Projectiles
}
}
if (hitanim != null)
hitanim.Tick();
hitanim?.Tick();
if (ticks++ > info.Duration && animationComplete)
world.AddFrameEndTask(w => w.Remove(this));

View File

@@ -31,8 +31,7 @@ namespace OpenRA.Mods.Common.Activities
{
try
{
if (function != null)
function.Call().Dispose();
function?.Call().Dispose();
}
catch (Exception ex)
{

View File

@@ -29,14 +29,7 @@ namespace OpenRA.Mods.Common.Scripting
[Desc("Creates a new radar ping that stays for the specified time at the specified WPos.")]
public void Ping(Player player, WPos position, Color color, int duration = 30 * 25)
{
if (radarPings != null)
{
radarPings.Add(
() => player.World.RenderPlayer == player,
position,
color,
duration);
}
radarPings?.Add(() => player.World.RenderPlayer == player, position, color, duration);
}
}
}

View File

@@ -54,8 +54,7 @@ namespace OpenRA.Mods.Common.Scripting
if (disposed)
return;
if (context != null)
context.Dispose();
context?.Dispose();
disposed = true;
}

View File

@@ -172,10 +172,7 @@ namespace OpenRA.Mods.Common.Scripting
{
get
{
if (autotarget == null)
return null;
return autotarget.Stance.ToString();
return autotarget?.Stance.ToString();
}
set
@@ -197,10 +194,8 @@ namespace OpenRA.Mods.Common.Scripting
get
{
var tooltip = tooltips.FirstEnabledTraitOrDefault();
if (tooltip == null)
return null;
return tooltip.Info.Name;
return tooltip?.Info.Name;
}
}

View File

@@ -98,8 +98,7 @@ namespace OpenRA.Mods.Common.Server
public void GameEnded(S server)
{
if (LanGameBeacon != null)
LanGameBeacon.Stop();
LanGameBeacon?.Stop();
lastChanged = Game.RunTime;
}

View File

@@ -18,8 +18,7 @@ namespace OpenRA.Mods.Common.Traits.BotModules.Squads
public void Update(Squad squad)
{
if (currentState != null)
currentState.Tick(squad);
currentState?.Tick(squad);
}
public void ChangeState(Squad squad, IState newState, bool rememberPrevious)
@@ -27,14 +26,12 @@ namespace OpenRA.Mods.Common.Traits.BotModules.Squads
if (rememberPrevious)
previousState = currentState;
if (currentState != null)
currentState.Deactivate(squad);
currentState?.Deactivate(squad);
if (newState != null)
currentState = newState;
if (currentState != null)
currentState.Activate(squad);
currentState?.Activate(squad);
}
public void RevertToPreviousState(Squad squad, bool saveCurrentState)

View File

@@ -302,8 +302,7 @@ namespace OpenRA.Mods.Common.Traits
// If this bridge repair operation connects two pathfinding domains,
// update the domain index.
var domainIndex = self.World.WorldActor.TraitOrDefault<DomainIndex>();
if (domainIndex != null)
domainIndex.UpdateCells(self.World, footprint.Keys);
domainIndex?.UpdateCells(self.World, footprint.Keys);
if (LongBridgeSegmentIsDead() && !killedUnits)
{

View File

@@ -70,9 +70,7 @@ namespace OpenRA.Mods.Common.Traits
foreach (var cell in cells)
self.World.Map.CustomTerrain[cell] = terrainIndex;
var domainIndex = self.World.WorldActor.TraitOrDefault<DomainIndex>();
if (domainIndex != null)
domainIndex.UpdateCells(self.World, cells);
self.World.WorldActor.TraitOrDefault<DomainIndex>()?.UpdateCells(self.World, cells);
}
void INotifyAddedToWorld.AddedToWorld(Actor self)

View File

@@ -91,10 +91,7 @@ namespace OpenRA.Mods.Common.Traits
void INotifyLineBuildSegmentsChanged.SegmentRemoved(Actor self, Actor segment)
{
if (segments == null)
return;
segments.Remove(segment);
segments?.Remove(segment);
}
void INotifyAddedToWorld.AddedToWorld(Actor self)

View File

@@ -172,9 +172,7 @@ namespace OpenRA.Mods.Common.Traits
if (r == self.Owner)
return;
var exp = r.PlayerActor.TraitOrDefault<PlayerExperience>();
if (exp != null)
exp.GiveExperience(Info.PlayerExperience);
r.PlayerActor.TraitOrDefault<PlayerExperience>()?.GiveExperience(Info.PlayerExperience);
});
Repairers.Clear();

View File

@@ -131,8 +131,8 @@ namespace OpenRA.Mods.Common.Traits
// Manually manage the inner activity queue
var activity = currentTransform ?? transform.GetTransformActivity(self);
if (!order.Queued && activity.NextActivity != null)
activity.NextActivity.Cancel(self);
if (!order.Queued)
activity.NextActivity?.Cancel(self);
activity.Queue(new IssueOrderAfterTransform(order.OrderString, order.Target, Color.Green));

View File

@@ -95,8 +95,8 @@ namespace OpenRA.Mods.Common.Traits
// Manually manage the inner activity queue
var activity = currentTransform ?? transform.GetTransformActivity(self);
if (!order.Queued && activity.NextActivity != null)
activity.NextActivity.Cancel(self);
if (!order.Queued)
activity.NextActivity?.Cancel(self);
activity.Queue(new IssueOrderAfterTransform(order.OrderString, order.Target, Color.Green));

View File

@@ -110,8 +110,8 @@ namespace OpenRA.Mods.Common.Traits
// Manually manage the inner activity queue
var activity = currentTransform ?? transform.GetTransformActivity(self);
if (!order.Queued && activity.NextActivity != null)
activity.NextActivity.Cancel(self);
if (!order.Queued)
activity.NextActivity?.Cancel(self);
activity.Queue(new IssueOrderAfterTransform("Move", order.Target, Color.Green));

View File

@@ -129,8 +129,8 @@ namespace OpenRA.Mods.Common.Traits
// Manually manage the inner activity queue
var activity = currentTransform ?? transform.GetTransformActivity(self);
if (!order.Queued && activity.NextActivity != null)
activity.NextActivity.Cancel(self);
if (!order.Queued)
activity.NextActivity?.Cancel(self);
activity.Queue(new IssueOrderAfterTransform(order.OrderString, order.Target, Color.Green));

View File

@@ -123,8 +123,8 @@ namespace OpenRA.Mods.Common.Traits
// Manually manage the inner activity queue
var activity = currentTransform ?? transform.GetTransformActivity(self);
if (!order.Queued && activity.NextActivity != null)
activity.NextActivity.Cancel(self);
if (!order.Queued)
activity.NextActivity?.Cancel(self);
activity.Queue(new IssueOrderAfterTransform(order.OrderString, order.Target, Color.Green));

View File

@@ -41,8 +41,8 @@ namespace OpenRA.Mods.Common.Traits
if (!order.Queued || currentTransform == null)
return;
if (!order.Queued && currentTransform.NextActivity != null)
currentTransform.NextActivity.Cancel(self);
if (!order.Queued)
currentTransform.NextActivity?.Cancel(self);
currentTransform.Queue(new IssueOrderAfterTransform("DeployTransform", order.Target, Color.Green));

View File

@@ -44,20 +44,16 @@ namespace OpenRA.Mods.Common.Traits
void INotifyCrushed.OnCrush(Actor self, Actor crusher, BitSet<CrushClass> crushClasses)
{
var external = crusher.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == Info.OnCrushCondition && t.CanGrantCondition(crusher, self));
if (external != null)
external.GrantCondition(crusher, self, Info.OnCrushDuration);
crusher.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == Info.OnCrushCondition && t.CanGrantCondition(crusher, self))
?.GrantCondition(crusher, self, Info.OnCrushDuration);
}
void INotifyCrushed.WarnCrush(Actor self, Actor crusher, BitSet<CrushClass> crushClasses)
{
var external = crusher.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == Info.WarnCrushCondition && t.CanGrantCondition(crusher, self));
if (external != null)
external.GrantCondition(crusher, self, Info.WarnCrushDuration);
crusher.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == Info.WarnCrushCondition && t.CanGrantCondition(crusher, self))
?.GrantCondition(crusher, self, Info.WarnCrushDuration);
}
}
}

View File

@@ -36,11 +36,9 @@ namespace OpenRA.Mods.Common.Traits
if (IsTraitDisabled || other.IsDead)
return;
var external = other.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == Info.Condition && t.CanGrantCondition(other, self));
if (external != null)
external.GrantCondition(other, self, Info.Duration);
other.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == Info.Condition && t.CanGrantCondition(other, self))
?.GrantCondition(other, self, Info.Duration);
}
}
}

View File

@@ -248,9 +248,7 @@ namespace OpenRA.Mods.Common.Traits
{
self.World.AddToMaps(self, this);
var cs = self.World.WorldActor.TraitOrDefault<CrateSpawner>();
if (cs != null)
cs.IncrementCrates();
self.World.WorldActor.TraitOrDefault<CrateSpawner>()?.IncrementCrates();
if (self.World.Map.DistanceAboveTerrain(CenterPosition) > WDist.Zero && self.TraitOrDefault<Parachutable>() != null)
self.QueueActivity(new Parachute(self));
@@ -260,9 +258,7 @@ namespace OpenRA.Mods.Common.Traits
{
self.World.RemoveFromMaps(self, this);
var cs = self.World.WorldActor.TraitOrDefault<CrateSpawner>();
if (cs != null)
cs.DecrementCrates();
self.World.WorldActor.TraitOrDefault<CrateSpawner>()?.DecrementCrates();
}
}
}

View File

@@ -72,9 +72,7 @@ namespace OpenRA.Mods.Common.Traits
var recipient = actor; // loop variable in closure hazard
recipient.World.AddFrameEndTask(w =>
{
var gainsExperience = recipient.TraitOrDefault<GainsExperience>();
if (gainsExperience != null)
gainsExperience.GiveLevels(info.Levels);
recipient.TraitOrDefault<GainsExperience>()?.GiveLevels(info.Levels);
});
}

View File

@@ -90,11 +90,7 @@ namespace OpenRA.Mods.Common.Traits
var pilot = self.World.CreateActor(true, Info.PilotActor.ToLowerInvariant(), td);
if (!inAir)
{
var pilotMobile = pilot.TraitOrDefault<Mobile>();
if (pilotMobile != null)
pilotMobile.Nudge(pilot);
}
pilot.TraitOrDefault<Mobile>()?.Nudge(pilot);
else
Game.Sound.Play(SoundType.World, Info.ChuteSound, cp);
});

View File

@@ -66,9 +66,8 @@ namespace OpenRA.Mods.Common.Traits
killer.GiveExperience(Util.ApplyPercentageModifiers(exp, killerExperienceModifier));
}
var attackerExp = e.Attacker.Owner.PlayerActor.TraitOrDefault<PlayerExperience>();
if (attackerExp != null)
attackerExp.GiveExperience(Util.ApplyPercentageModifiers(exp, new[] { info.PlayerExperienceModifier }));
e.Attacker.Owner.PlayerActor.TraitOrDefault<PlayerExperience>()
?.GiveExperience(Util.ApplyPercentageModifiers(exp, new[] { info.PlayerExperienceModifier }));
}
}
}

View File

@@ -26,9 +26,7 @@ namespace OpenRA.Mods.Common.Traits
if (!building.AppearsFriendlyTo(self))
return;
var rb = building.TraitOrDefault<RepairableBuilding>();
if (rb != null)
rb.RepairBuilding(building, self.Owner);
building.TraitOrDefault<RepairableBuilding>()?.RepairBuilding(building, self.Owner);
}
}
}

View File

@@ -80,8 +80,7 @@ namespace OpenRA.Mods.Common.Traits
if (p != self.Owner && p.IsAlliedWith(self.Owner) && p != e.Attacker.Owner)
Game.Sound.PlayNotification(rules, p, "Speech", info.AllyNotification, p.Faction.InternalName);
if (radarPings != null)
radarPings.Add(() => self.Owner.IsAlliedWith(self.World.RenderPlayer), self.CenterPosition, info.RadarPingColor, info.RadarPingDuration);
radarPings?.Add(() => self.Owner.IsAlliedWith(self.World.RenderPlayer), self.CenterPosition, info.RadarPingColor, info.RadarPingDuration);
}
lastAttackTime = self.World.WorldTick;

View File

@@ -244,10 +244,7 @@ namespace OpenRA.Mods.Common.Traits
case "DevPlayerExperience":
{
var playerExperience = self.Owner.PlayerActor.TraitOrDefault<PlayerExperience>();
if (playerExperience != null)
playerExperience.GiveExperience((int)order.ExtraData);
self.Owner.PlayerActor.TraitOrDefault<PlayerExperience>()?.GiveExperience((int)order.ExtraData);
break;
}

View File

@@ -61,8 +61,7 @@ namespace OpenRA.Mods.Common.Traits
{
Game.Sound.PlayNotification(self.World.Map.Rules, self.Owner, "Speech", info.Notification, self.Owner.Faction.InternalName);
if (radarPings != null)
radarPings.Add(() => self.Owner.IsAlliedWith(self.World.RenderPlayer), self.CenterPosition, info.RadarPingColor, info.RadarPingDuration);
radarPings?.Add(() => self.Owner.IsAlliedWith(self.World.RenderPlayer), self.CenterPosition, info.RadarPingColor, info.RadarPingDuration);
}
lastAttackTime = self.World.WorldTick;

View File

@@ -170,8 +170,7 @@ namespace OpenRA.Mods.Common.Traits
foreach (var t in buildingInfo.Tiles(targetLocation))
{
var host = buildingInfluence.GetBuildingAt(t);
if (host != null)
host.World.Remove(host);
host?.World.Remove(host);
}
}
@@ -193,14 +192,10 @@ namespace OpenRA.Mods.Common.Traits
queue.EndProduction(item);
// FindBaseProvider may return null if the build anywhere cheat is active
// BuildingInfo.IsCloseEnoughToBase has already verified that this is a valid build location
if (buildingInfo.RequiresBaseProvider)
{
// May be null if the build anywhere cheat is active
// BuildingInfo.IsCloseEnoughToBase has already verified that this is a valid build location
var provider = buildingInfo.FindBaseProvider(w, self.Owner, targetLocation);
if (provider != null)
provider.BeginCooldown();
}
buildingInfo.FindBaseProvider(w, self.Owner, targetLocation)?.BeginCooldown();
if (GetNumBuildables(self.Owner) > prevItems)
triggerNotification = true;

View File

@@ -61,8 +61,7 @@ namespace OpenRA.Mods.Common.Traits
{
terrainColor[uv] = GetColor(world.Map, uv);
if (CellTerrainColorChanged != null)
CellTerrainColorChanged(uv);
CellTerrainColorChanged?.Invoke(uv);
}
public void WorldLoaded(World w, WorldRenderer wr)

View File

@@ -465,9 +465,7 @@ namespace OpenRA.Mods.Common.Traits
protected void PauseProduction(string itemName, bool paused)
{
var item = Queue.FirstOrDefault(a => a.Item == itemName);
if (item != null)
item.Pause(paused);
Queue.FirstOrDefault(a => a.Item == itemName)?.Pause(paused);
}
protected void CancelProduction(string itemName, uint numberToCancel)
@@ -646,8 +644,7 @@ namespace OpenRA.Mods.Common.Traits
if (Done)
{
if (OnComplete != null)
OnComplete();
OnComplete?.Invoke();
return;
}

View File

@@ -105,14 +105,11 @@ namespace OpenRA.Mods.Common.Traits.Render
{
Reverse(self, () =>
{
var wsb = wsbs.FirstEnabledTraitOrDefault();
// HACK: The actor remains alive and active for one tick before the followup activity
// (sell/transform/etc) runs. This causes visual glitches that we attempt to minimize
// by forcing the animation to frame 0 and regranting the make condition.
// These workarounds will break the actor if the followup activity doesn't dispose it!
if (wsb != null)
wsb.DefaultAnimation.PlayFetchIndex(info.Sequence, () => 0);
wsbs.FirstEnabledTraitOrDefault()?.DefaultAnimation.PlayFetchIndex(info.Sequence, () => 0);
token = self.GrantCondition(info.Condition);

View File

@@ -159,8 +159,7 @@ namespace OpenRA.Mods.Common.Traits.Render
void ITick.Tick(Actor self)
{
if (shadow != null)
shadow.Tick();
shadow?.Tick();
}
IEnumerable<IRenderable> IRender.Render(Actor self, WorldRenderer wr)

View File

@@ -97,8 +97,7 @@ namespace OpenRA.Mods.Common.Traits.Render
DefaultAnimation.PlayThen(NormalizeSequence(self, name), () =>
{
CancelCustomAnimation(self);
if (after != null)
after();
after?.Invoke();
});
}
@@ -112,8 +111,7 @@ namespace OpenRA.Mods.Common.Traits.Render
DefaultAnimation.PlayBackwardsThen(NormalizeSequence(self, name), () =>
{
CancelCustomAnimation(self);
if (after != null)
after();
after?.Invoke();
});
}

View File

@@ -132,8 +132,7 @@ namespace OpenRA.Mods.Common.Traits.Render
DefaultAnimation.PlayThen(NormalizeSequence(self, name), () =>
{
CancelCustomAnimation(self);
if (after != null)
after();
after?.Invoke();
});
}

View File

@@ -57,8 +57,8 @@ namespace OpenRA.Mods.Common.Traits.Sound
Game.Sound.PlayNotification(self.World.Map.Rules, discoverer, "Speech", Info.Notification, discoverer.Faction.InternalName);
// Radar notification
if (Info.PingRadar && radarPings.Value != null)
radarPings.Value.Add(() => true, self.CenterPosition, Color.Red, 50);
if (Info.PingRadar)
radarPings.Value?.Add(() => true, self.CenterPosition, Color.Red, 50);
}
}
}

View File

@@ -83,13 +83,9 @@ namespace OpenRA.Mods.Common.Traits
Game.Sound.Play(SoundType.World, info.OnFireSound, order.Target.CenterPosition);
foreach (var a in UnitsInRange(self.World.Map.CellContaining(order.Target.CenterPosition)))
{
var external = a.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == info.Condition && t.CanGrantCondition(a, self));
if (external != null)
external.GrantCondition(a, self, info.Duration);
}
a.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == info.Condition && t.CanGrantCondition(a, self))
?.GrantCondition(a, self, info.Duration);
}
public IEnumerable<Actor> UnitsInRange(CPos xy)

View File

@@ -227,10 +227,8 @@ namespace OpenRA.Mods.Common.Traits
return;
var power = Instances.FirstOrDefault(i => !i.IsTraitPaused);
if (power == null)
return;
power.SelectTarget(power.Self, Key, Manager);
power?.SelectTarget(power.Self, Key, Manager);
}
public virtual void Activate(Order order)

View File

@@ -381,8 +381,7 @@ namespace OpenRA.Mods.Common.Traits
foreach (var t in triggers)
t.Dirty = true;
if (CellUpdated != null)
CellUpdated(c.Cell);
CellUpdated?.Invoke(c.Cell);
}
}
@@ -403,8 +402,7 @@ namespace OpenRA.Mods.Common.Traits
foreach (var t in triggers)
t.Dirty = true;
if (CellUpdated != null)
CellUpdated(c.Cell);
CellUpdated?.Invoke(c.Cell);
}
}

View File

@@ -49,8 +49,7 @@ namespace OpenRA.Mods.Common.Traits
ClearRedo();
undoStack.Push(actionContainer);
if (ItemAdded != null)
ItemAdded(actionContainer);
ItemAdded?.Invoke(actionContainer);
}
public void Undo()
@@ -66,8 +65,7 @@ namespace OpenRA.Mods.Common.Traits
editorAction.Status = EditorActionStatus.Future;
redoStack.Push(editorAction);
if (OnChange != null)
OnChange();
OnChange?.Invoke();
}
void ClearRedo()
@@ -76,8 +74,7 @@ namespace OpenRA.Mods.Common.Traits
{
var item = redoStack.Pop();
if (ItemRemoved != null)
ItemRemoved(item);
ItemRemoved?.Invoke(item);
}
}
@@ -95,8 +92,7 @@ namespace OpenRA.Mods.Common.Traits
undoStack.Peek().Status = EditorActionStatus.History;
undoStack.Push(editorAction);
if (OnChange != null)
OnChange();
OnChange?.Invoke();
}
public bool HasUndos()

View File

@@ -92,8 +92,7 @@ namespace OpenRA.Mods.Common.Traits
UpdateNetWorth(t.Type, t.Density, newTile.Type, newTile.Density);
Tiles[uv] = newTile;
Map.CustomTerrain[uv] = newTerrain;
if (CellChanged != null)
CellChanged(cell, type);
CellChanged?.Invoke(cell, type);
// Neighbouring cell density depends on this cell
foreach (var d in CVec.Directions)
@@ -111,8 +110,7 @@ namespace OpenRA.Mods.Common.Traits
neighbouringTile.Density = density;
Tiles[neighbouringCell] = neighbouringTile;
if (CellChanged != null)
CellChanged(neighbouringCell, type);
CellChanged?.Invoke(neighbouringCell, type);
}
}

View File

@@ -158,8 +158,7 @@ namespace OpenRA.Mods.Common.Traits
cell.Density = Math.Min(cell.Type.Info.MaxDensity, cell.Density + n);
Content[p] = cell;
if (CellChanged != null)
CellChanged(p, cell.Type);
CellChanged?.Invoke(p, cell.Type);
}
public bool IsFull(CPos cell)
@@ -183,8 +182,7 @@ namespace OpenRA.Mods.Common.Traits
else
Content[cell] = c;
if (CellChanged != null)
CellChanged(cell, c.Type);
CellChanged?.Invoke(cell, c.Type);
return c.Type;
}
@@ -202,8 +200,7 @@ namespace OpenRA.Mods.Common.Traits
Content[cell] = ResourceLayerContents.Empty;
world.Map.CustomTerrain[cell] = byte.MaxValue;
if (CellChanged != null)
CellChanged(cell, c.Type);
CellChanged?.Invoke(cell, c.Type);
}
public ResourceType GetResourceType(CPos cell) { return Content[cell].Type; }

View File

@@ -70,8 +70,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules
foreach (var sequence in sequenceNode.Value.Nodes)
{
var facingFudgeNode = sequence.LastChildMatching("UseClassicFacingFudge");
if (facingFudgeNode != null)
facingFudgeNode.RenameKey("UseClassicFacings");
facingFudgeNode?.RenameKey("UseClassicFacings");
}
yield break;

View File

@@ -263,8 +263,7 @@ namespace OpenRA.Mods.Common.UpdateRules
public static void Save(this YamlFileSet files)
{
foreach (var file in files)
if (file.Item1 != null)
file.Item1.Update(file.Item2, Encoding.UTF8.GetBytes(file.Item3.WriteToString()));
file.Item1?.Update(file.Item2, Encoding.UTF8.GetBytes(file.Item3.WriteToString()));
}
/// <summary>Checks if node is a removal (has '-' prefix)</summary>

View File

@@ -38,11 +38,9 @@ namespace OpenRA.Mods.Common.Warheads
if (!IsValidAgainst(a, firedBy))
continue;
var external = a.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == Condition && t.CanGrantCondition(a, firedBy));
if (external != null)
external.GrantCondition(a, firedBy, Duration);
a.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == Condition && t.CanGrantCondition(a, firedBy))
?.GrantCondition(a, firedBy, Duration);
}
}
}

View File

@@ -71,8 +71,7 @@ namespace OpenRA.Mods.Common.Widgets
cancelButton.OnClick = () =>
{
Ui.CloseWindow();
if (onCancel != null)
onCancel();
onCancel?.Invoke();
};
if (!string.IsNullOrEmpty(cancelText) && cancelButton != null)
@@ -85,8 +84,7 @@ namespace OpenRA.Mods.Common.Widgets
otherButton.Bounds.Y += headerHeight;
otherButton.OnClick = () =>
{
if (onOther != null)
onOther();
onOther?.Invoke();
};
if (!string.IsNullOrEmpty(otherText) && otherButton != null)
@@ -156,8 +154,7 @@ namespace OpenRA.Mods.Common.Widgets
cancelButton.OnClick = () =>
{
Ui.CloseWindow();
if (onCancel != null)
onCancel();
onCancel?.Invoke();
};
// Validation

View File

@@ -129,9 +129,7 @@ namespace OpenRA.Mods.Common.Widgets
oldBounds.Height);
panelRoot.AddChild(panel);
var scrollPanel = panel as ScrollPanelWidget;
if (scrollPanel != null)
scrollPanel.ScrollToSelectedItem();
(panel as ScrollPanelWidget)?.ScrollToSelectedItem();
}
public void ShowDropDown<T>(string panelTemplate, int maxHeight, IEnumerable<T> options, Func<T, ScrollItemWidget, ScrollItemWidget> setupItem)

View File

@@ -52,8 +52,7 @@ namespace OpenRA.Mods.Common.Widgets
public void ClearBrush() { SetBrush(null); }
public void SetBrush(IEditorBrush brush)
{
if (CurrentBrush != null)
CurrentBrush.Dispose();
CurrentBrush?.Dispose();
CurrentBrush = brush ?? DefaultBrush;
}

View File

@@ -40,8 +40,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
foreach (var o in api.ActorPreviewInits(actor, ActorPreviewType.ColorPicker))
td.Add(o);
if (preview != null)
preview.SetPreview(actor, td);
preview?.SetPreview(actor, td);
var hueSlider = widget.Get<SliderWidget>("HUE");
var mixer = widget.Get<ColorMixerWidget>("MIXER");

View File

@@ -375,8 +375,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
void Reset()
{
if (editActorPreview != null)
editActorPreview.Reset();
editActorPreview?.Reset();
}
void Close()

View File

@@ -71,8 +71,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
categorySelector.OnMouseDown = _ =>
{
if (SearchTextField != null)
SearchTextField.YieldKeyboardFocus();
SearchTextField?.YieldKeyboardFocus();
categorySelector.RemovePanel();
categorySelector.AttachPanel(CreateCategoriesPanel(Panel));

View File

@@ -233,8 +233,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
public void AddChatLineWrapper(string name, Color nameColor, string text, Color textColor)
{
if (chatOverlayDisplay != null)
chatOverlayDisplay.AddLine(name, nameColor, text, textColor);
chatOverlayDisplay?.AddLine(name, nameColor, text, textColor);
// HACK: Force disable the chat notification sound for the in-menu chat dialog
// This works around our inability to disable the sounds for the in-game dialog when it is hidden

View File

@@ -64,8 +64,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
menu = widget.Get("INGAME_MENU");
mpe = world.WorldActor.TraitOrDefault<MenuPaletteEffect>();
if (mpe != null)
mpe.Fade(mpe.Info.MenuEffect);
mpe?.Fade(mpe.Info.MenuEffect);
menu.Get<LabelWidget>("VERSION_LABEL").Text = modData.Manifest.Metadata.Version;
@@ -158,8 +157,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
void CloseMenu()
{
Ui.CloseWindow();
if (mpe != null)
mpe.Fade(MenuPaletteEffect.EffectType.None);
mpe?.Fade(MenuPaletteEffect.EffectType.None);
onExit();
}

View File

@@ -317,8 +317,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
output.Write(buffer, 0, write);
copied += write;
if (onProgress != null)
onProgress(copied);
onProgress?.Invoke(copied);
}
}
@@ -375,15 +374,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
{
Log.Write("install", "Extracting {0} -> {1}".F(sourcePath, targetPath));
if (type == ExtractionType.Blast)
{
Action<long, long> onBlastProgress = (read, _) =>
{
if (onProgress != null)
onProgress(read);
};
Blast.Decompress(source, target, onBlastProgress);
}
Blast.Decompress(source, target, (read, _) => onProgress?.Invoke(read));
else
CopyStream(source, target, length, onProgress);
}

View File

@@ -330,8 +330,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
onConfirm: () =>
{
var newUid = DeleteMap(map);
if (after != null)
after(newUid);
after?.Invoke(newUid);
},
confirmText: "Delete",
onCancel: () => { });
@@ -345,8 +344,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
onConfirm: () =>
{
maps.Do(m => DeleteMap(m));
if (after != null)
after(Game.ModData.MapCache.ChooseInitialMap(null, Game.CosmeticRandom));
after?.Invoke(Game.ModData.MapCache.ChooseInitialMap(null, Game.CosmeticRandom));
},
confirmText: "Delete",
onCancel: () => { });

View File

@@ -350,8 +350,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
player.PlayThen(() =>
{
StopVideo(player);
if (onComplete != null)
onComplete();
onComplete?.Invoke();
});
// Mute other distracting sounds

View File

@@ -415,8 +415,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
onConfirm: () =>
{
DeleteReplay(r);
if (after != null)
after.Invoke();
after?.Invoke();
},
confirmText: "Delete",
onCancel: () => { });

View File

@@ -541,8 +541,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
foreach (var row in rows)
serverList.AddChild(row);
if (nextServerRow != null)
nextServerRow.OnClick();
nextServerRow?.OnClick();
playerCount = games.Sum(g => g.Players);
});
@@ -744,8 +743,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
if (disposing && !disposed)
{
disposed = true;
if (lanGameProbe != null)
lanGameProbe.Dispose();
lanGameProbe?.Dispose();
}
base.Dispose(disposing);