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

@@ -185,8 +185,7 @@ namespace OpenRA.Activities
/// </summary>
internal void OnActorDisposeOuter(Actor self)
{
if (ChildActivity != null)
ChildActivity.OnActorDisposeOuter(self);
ChildActivity?.OnActorDisposeOuter(self);
OnActorDispose(self);
}
@@ -199,8 +198,7 @@ namespace OpenRA.Activities
if (!IsInterruptible)
return;
if (ChildActivity != null)
ChildActivity.Cancel(self);
ChildActivity?.Cancel(self);
// Directly mark activities that are queued and therefore didn't run yet as done
State = State == ActivityState.Queued ? ActivityState.Done : ActivityState.Canceling;
@@ -243,11 +241,9 @@ namespace OpenRA.Activities
Console.WriteLine(GetType().ToString().Split('.').Last());
if (ChildActivity != null)
ChildActivity.PrintActivityTree(self, origin, level + 1);
ChildActivity?.PrintActivityTree(self, origin, level + 1);
if (NextActivity != null)
NextActivity.PrintActivityTree(self, origin, level);
NextActivity?.PrintActivityTree(self, origin, level);
}
}

View File

@@ -26,7 +26,7 @@ namespace OpenRA.Activities
public override bool Tick(Actor self)
{
if (a != null) a();
a?.Invoke();
return true;
}
}

View File

@@ -329,8 +329,7 @@ namespace OpenRA
public void CancelActivity()
{
if (CurrentActivity != null)
CurrentActivity.Cancel(this);
CurrentActivity?.Cancel(this);
}
public override int GetHashCode()
@@ -382,8 +381,7 @@ namespace OpenRA
{
// If CurrentActivity isn't null, run OnActorDisposeOuter in case some cleanups are needed.
// This should be done before the FrameEndTask to avoid dependency issues.
if (CurrentActivity != null)
CurrentActivity.OnActorDisposeOuter(this);
CurrentActivity?.OnActorDisposeOuter(this);
// Allow traits/activities to prevent a race condition when they depend on disposing the actor (e.g. Transforms)
WillDispose = true;
@@ -402,8 +400,7 @@ namespace OpenRA
World.TraitDict.RemoveActor(this);
Disposed = true;
if (luaInterface != null)
luaInterface.Value.OnActorDestroyed();
luaInterface?.Value.OnActorDestroyed();
});
}

View File

@@ -90,8 +90,7 @@ namespace OpenRA
public void CancelAsync()
{
lock (syncObject)
if (wc != null)
wc.CancelAsync();
wc?.CancelAsync();
}
}
}

View File

@@ -179,8 +179,7 @@ namespace OpenRA
public static object GetValue(string fieldName, Type fieldType, MiniYaml yaml, MemberInfo field)
{
var value = yaml.Value;
if (value != null) value = value.Trim();
var value = yaml.Value?.Trim();
if (fieldType == typeof(int))
{

View File

@@ -197,10 +197,7 @@ namespace OpenRA.FileSystem
var package = fileIndex[filename]
.LastOrDefault(x => x.Contains(filename));
if (package != null)
return package.GetStream(filename);
return null;
return package?.GetStream(filename);
}
public Stream Open(string filename)

View File

@@ -66,8 +66,7 @@ namespace OpenRA.FileSystem
public void Dispose()
{
if (pkg != null)
pkg.Close();
pkg?.Close();
}
public IReadOnlyPackage OpenPackage(string filename, FileSystem context)

View File

@@ -80,7 +80,7 @@ namespace OpenRA
static void JoinInner(OrderManager om)
{
if (OrderManager != null) OrderManager.Dispose();
OrderManager?.Dispose();
OrderManager = om;
lastConnectionState = ConnectionState.PreConnecting;
ConnectionStateChanged(OrderManager);
@@ -154,8 +154,7 @@ namespace OpenRA
internal static void StartGame(string mapUID, WorldType type)
{
// Dispose of the old world before creating a new one.
if (worldRenderer != null)
worldRenderer.Dispose();
worldRenderer?.Dispose();
Cursor.SetCursor(null);
BeforeGameStart();
@@ -330,11 +329,9 @@ namespace OpenRA
Log.Write("graphics", "{0}", e);
Console.WriteLine("Renderer initialization failed. Check graphics.log for details.");
if (Renderer != null)
Renderer.Dispose();
Renderer?.Dispose();
if (Sound != null)
Sound.Dispose();
Sound?.Dispose();
}
}
@@ -388,13 +385,10 @@ namespace OpenRA
Ui.ResetAll();
if (worldRenderer != null)
worldRenderer.Dispose();
worldRenderer?.Dispose();
worldRenderer = null;
if (server != null)
server.Shutdown();
if (OrderManager != null)
OrderManager.Dispose();
server?.Shutdown();
OrderManager?.Dispose();
if (ModData != null)
{
@@ -430,8 +424,7 @@ namespace OpenRA
var grid = ModData.Manifest.Contains<MapGrid>() ? ModData.Manifest.Get<MapGrid>() : null;
Renderer.InitializeDepthBuffer(grid);
if (Cursor != null)
Cursor.Dispose();
Cursor?.Dispose();
Cursor = new CursorManager(ModData.CursorProvider);
@@ -446,8 +439,7 @@ namespace OpenRA
try
{
if (discoverNat != null)
discoverNat.Wait();
discoverNat?.Wait();
}
catch (Exception e)
{
@@ -610,8 +602,7 @@ namespace OpenRA
Sync.RunUnsynced(Settings.Debug.SyncCheckUnsyncedCode, world, () => world.TickRender(worldRenderer));
}
if (benchmark != null)
benchmark.Tick(LocalTick);
benchmark?.Tick(LocalTick);
}
}
@@ -836,12 +827,10 @@ namespace OpenRA
finally
{
// Ensure that the active replay is properly saved
if (OrderManager != null)
OrderManager.Dispose();
OrderManager?.Dispose();
}
if (worldRenderer != null)
worldRenderer.Dispose();
worldRenderer?.Dispose();
ModData.Dispose();
ChromeProvider.Deinitialize();
@@ -880,8 +869,7 @@ namespace OpenRA
public static void Disconnect()
{
if (OrderManager.World != null)
OrderManager.World.TraitDict.PrintReport();
OrderManager.World?.TraitDict.PrintReport();
OrderManager.Dispose();
CloseServer();
@@ -890,8 +878,7 @@ namespace OpenRA
public static void CloseServer()
{
if (server != null)
server.Shutdown();
server?.Shutdown();
}
public static T CreateObject<T>(string name)

View File

@@ -156,7 +156,7 @@ namespace OpenRA.Graphics
{
frame = CurrentSequence.Length - 1;
tickFunc = () => { };
if (after != null) after();
after?.Invoke();
}
};
}

View File

@@ -146,8 +146,7 @@ namespace OpenRA.Graphics
public void Dispose()
{
if (texture != null)
texture.Dispose();
texture?.Dispose();
}
}
}

View File

@@ -97,8 +97,8 @@ namespace OpenRA.Graphics
var oldHeight = palette.Height;
palette.AddPalette(name, pal, allowModifiers);
if (oldHeight != palette.Height && PaletteInvalidated != null)
PaletteInvalidated();
if (oldHeight != palette.Height)
PaletteInvalidated?.Invoke();
}
}
@@ -258,8 +258,7 @@ namespace OpenRA.Graphics
if (enableDepthBuffer)
Game.Renderer.Context.EnableDepthBuffer();
if (terrainRenderer != null)
terrainRenderer.RenderTerrain(this, Viewport);
terrainRenderer?.RenderTerrain(this, Viewport);
Game.Renderer.Flush();

View File

@@ -78,8 +78,7 @@ namespace OpenRA
Log.Write("debug", "Load mod '{0}': {1}".F(path, e));
}
if (package != null)
package.Dispose();
package?.Dispose();
return null;
}

View File

@@ -108,8 +108,7 @@ namespace OpenRA
}
finally
{
if (onComplete != null)
onComplete();
onComplete?.Invoke();
}
};

View File

@@ -245,8 +245,7 @@ namespace OpenRA
foreach (var module in modules)
{
var disposableModule = module as IDisposable;
if (disposableModule != null)
disposableModule.Dispose();
disposableModule?.Dispose();
}
}
}

View File

@@ -73,8 +73,7 @@ namespace OpenRA
{
entries[Index(cell)] = value;
if (CellEntryChanged != null)
CellEntryChanged(cell);
CellEntryChanged?.Invoke(cell);
}
}
@@ -90,8 +89,7 @@ namespace OpenRA
{
entries[Index(uv)] = value;
if (CellEntryChanged != null)
CellEntryChanged(uv.ToCPos(GridType));
CellEntryChanged?.Invoke(uv.ToCPos(GridType));
}
}

View File

@@ -111,8 +111,7 @@ namespace OpenRA
}
catch (Exception e)
{
if (mapPackage != null)
mapPackage.Dispose();
mapPackage?.Dispose();
Console.WriteLine("Failed to load map: {0}", map);
Console.WriteLine("Details: {0}", e);
Log.Write("debug", "Failed to load map: {0}", map);
@@ -192,8 +191,7 @@ namespace OpenRA
foreach (var p in maps.Values)
p.UpdateRemoteSearch(MapStatus.Unavailable, null);
if (queryFailed != null)
queryFailed();
queryFailed?.Invoke();
return;
}
@@ -213,8 +211,7 @@ namespace OpenRA
{
Log.Write("debug", "Can't parse remote map search data:\n{0}", data);
Log.Write("debug", "Exception: {0}", e);
if (queryFailed != null)
queryFailed();
queryFailed?.Invoke();
}
};
@@ -298,8 +295,7 @@ namespace OpenRA
Game.RunAfterTick(() =>
{
// Wait for any existing thread to exit before starting a new one.
if (previewLoaderThread != null)
previewLoaderThread.Join();
previewLoaderThread?.Join();
previewLoaderThread = new Thread(LoadAsyncInternal)
{

View File

@@ -412,8 +412,7 @@ namespace OpenRA
if (innerData.Preview != null)
cache.CacheMinimap(this);
if (parseMetadata != null)
parseMetadata(this);
parseMetadata?.Invoke(this);
}
// Update the status and class unconditionally
@@ -522,9 +521,7 @@ namespace OpenRA
public void Delete()
{
Invalidate();
var deleteFromPackage = parentPackage as IReadWritePackage;
if (deleteFromPackage != null)
deleteFromPackage.Delete(Package.Name);
(parentPackage as IReadWritePackage)?.Delete(Package.Name);
}
Stream IReadOnlyFileSystem.Open(string filename)

View File

@@ -177,8 +177,7 @@ namespace OpenRA
public Map PrepareMap(string uid)
{
if (LoadScreen != null)
LoadScreen.Display();
LoadScreen?.Display();
if (MapCache[uid].Status != MapStatus.Available)
throw new InvalidDataException("Invalid map uid: {0}".F(uid));
@@ -202,12 +201,10 @@ namespace OpenRA
public void Dispose()
{
if (LoadScreen != null)
LoadScreen.Dispose();
LoadScreen?.Dispose();
MapCache.Dispose();
if (ObjectCreator != null)
ObjectCreator.Dispose();
ObjectCreator?.Dispose();
Manifest.Dispose();
}

View File

@@ -174,23 +174,21 @@ namespace OpenRA.Network
foreach (var p in packets)
{
packetFn(p.FromClient, p.Data);
if (Recorder != null)
Recorder.Receive(p.FromClient, p.Data);
Recorder?.Receive(p.FromClient, p.Data);
}
}
public void StartRecording(Func<string> chooseFilename)
{
// If we have a previous recording then save/dispose it and start a new one.
if (Recorder != null)
Recorder.Dispose();
Recorder?.Dispose();
Recorder = new ReplayRecorder(chooseFilename);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && Recorder != null)
Recorder.Dispose();
if (disposing)
Recorder?.Dispose();
}
public void Dispose()
@@ -372,8 +370,7 @@ namespace OpenRA.Network
// Closing the stream will cause any reads on the receiving thread to throw.
// This will mark the connection as no longer connected and the thread will terminate cleanly.
if (tcp != null)
tcp.Close();
tcp?.Close();
base.Dispose(disposing);
}

View File

@@ -206,8 +206,7 @@ namespace OpenRA.Network
public void Dispose()
{
disposed = true;
if (Connection != null)
Connection.Dispose();
Connection?.Dispose();
}
}

View File

@@ -100,8 +100,7 @@ namespace OpenRA.Network
Metadata.Write(writer);
}
if (preStartBuffer != null)
preStartBuffer.Dispose();
preStartBuffer?.Dispose();
writer.Close();
}
}

View File

@@ -145,8 +145,7 @@ namespace OpenRA.Network
var data = MiniYaml.FromString(order.TargetString)[0];
var traitIndex = int.Parse(data.Key);
if (world != null)
world.AddGameSaveTraitData(traitIndex, data.Value);
world?.AddGameSaveTraitData(traitIndex, data.Value);
break;
}

View File

@@ -67,10 +67,7 @@ namespace OpenRA
if (a.FullName == e.Name)
return a;
if (assemblies == null)
return null;
return assemblies.Select(a => a.Assembly).FirstOrDefault(a => a.FullName == e.Name);
return assemblies?.Select(a => a.Assembly).FirstOrDefault(a => a.FullName == e.Name);
}
// Only used by the linter to prevent exceptions from being thrown during a lint run

View File

@@ -115,8 +115,7 @@ namespace OpenRA
font.Dispose();
using (new PerfTimer("SpriteFonts"))
{
if (fontSheetBuilder != null)
fontSheetBuilder.Dispose();
fontSheetBuilder?.Dispose();
fontSheetBuilder = new SheetBuilder(SheetType.BGRA, 512);
Fonts = modData.Manifest.Get<Fonts>().FontList.ToDictionary(x => x.Key,
x => new SpriteFont(x.Value.Font, modData.DefaultFileSystem.Open(x.Value.Font).ReadAllBytes(),
@@ -156,8 +155,7 @@ namespace OpenRA
if (screenSprite == null || screenSprite.Sheet.Size != surfaceBufferSize)
{
if (screenBuffer != null)
screenBuffer.Dispose();
screenBuffer?.Dispose();
// Render the screen into a frame buffer to simplify reading back screenshots
screenBuffer = Context.CreateFrameBuffer(surfaceBufferSize, Color.FromArgb(0xFF, 0, 0, 0));
@@ -195,8 +193,7 @@ namespace OpenRA
var worldBufferSize = worldViewport.Size.NextPowerOf2();
if (worldSprite == null || worldSprite.Sheet.Size != worldBufferSize)
{
if (worldBuffer != null)
worldBuffer.Dispose();
worldBuffer?.Dispose();
// Render the world into a framebuffer at 1:1 scaling to allow the depth buffer to match the artwork at all zoom levels
worldBuffer = Context.CreateFrameBuffer(worldBufferSize);
@@ -329,8 +326,7 @@ namespace OpenRA
{
if (currentBatchRenderer == value)
return;
if (currentBatchRenderer != null)
currentBatchRenderer.Flush();
currentBatchRenderer?.Flush();
currentBatchRenderer = value;
}
}
@@ -460,8 +456,7 @@ namespace OpenRA
{
WorldModelRenderer.Dispose();
tempBuffer.Dispose();
if (fontSheetBuilder != null)
fontSheetBuilder.Dispose();
fontSheetBuilder?.Dispose();
if (Fonts != null)
foreach (var font in Fonts.Values)
font.Dispose();

View File

@@ -267,8 +267,7 @@ namespace OpenRA.Scripting
return;
disposed = true;
if (runtime != null)
runtime.Dispose();
runtime?.Dispose();
}
static IEnumerable<Type> ExtractRequiredTypes(Type t)

View File

@@ -168,8 +168,7 @@ namespace OpenRA.Scripting
{
// Object needs additional notification / context
var notify = obj as IScriptNotifyBind;
if (notify != null)
notify.OnScriptBind(context);
notify?.OnScriptBind(context);
return new LuaCustomClrObject(obj);
}

View File

@@ -244,8 +244,7 @@ namespace OpenRA.Server
}
var conn = Conns.SingleOrDefault(c => c.Socket == s);
if (conn != null)
conn.ReadData(this);
conn?.ReadData(this);
}
delayedActions.PerformActions(0);

View File

@@ -88,8 +88,7 @@ namespace OpenRA
if (sounds != null)
foreach (var soundSource in sounds.Values)
if (soundSource != null)
soundSource.Dispose();
soundSource?.Dispose();
this.loaders = loaders;
this.fileSystem = fileSystem;
@@ -430,8 +429,8 @@ namespace OpenRA
StopAudio();
if (sounds != null)
foreach (var soundSource in sounds.Values)
if (soundSource != null)
soundSource.Dispose();
soundSource?.Dispose();
soundEngine.Dispose();
}
}

View File

@@ -113,11 +113,9 @@ namespace OpenRA.Widgets
if (wasMouseOver != MouseOverWidget)
{
if (wasMouseOver != null)
wasMouseOver.MouseExited();
wasMouseOver?.MouseExited();
if (MouseOverWidget != null)
MouseOverWidget.MouseEntered();
MouseOverWidget?.MouseEntered();
}
return handled;

View File

@@ -50,8 +50,7 @@ namespace OpenRA
var widget = NewWidget(node.Key, args);
if (parent != null)
parent.AddChild(widget);
parent?.AddChild(widget);
if (node.Key.Contains("@"))
FieldLoader.LoadField(widget, "Id", node.Key.Split('@')[1]);

View File

@@ -89,8 +89,7 @@ namespace OpenRA
{
renderPlayer = value;
if (RenderPlayerChanged != null)
RenderPlayerChanged(value);
RenderPlayerChanged?.Invoke(value);
}
}
}
@@ -159,8 +158,7 @@ namespace OpenRA
set
{
Sync.AssertUnsynced("The current order generator may not be changed from synced code");
if (orderGenerator != null)
orderGenerator.Deactivate();
orderGenerator?.Deactivate();
orderGenerator = value;
}
@@ -581,8 +579,7 @@ namespace OpenRA
{
Disposing = true;
if (OrderGenerator != null)
OrderGenerator.Deactivate();
OrderGenerator?.Deactivate();
frameEndActions.Clear();

View File

@@ -65,8 +65,7 @@ namespace OpenRA.Mods.Cnc.Activities
t.Infiltrated(targetActor, self, infiltrates.Info.Types);
var exp = self.Owner.PlayerActor.TraitOrDefault<PlayerExperience>();
if (exp != null)
exp.GiveExperience(infiltrates.Info.PlayerExperience);
exp?.GiveExperience(infiltrates.Info.PlayerExperience);
if (!string.IsNullOrEmpty(infiltrates.Info.Notification))
Game.Sound.PlayNotification(self.World.Map.Rules, self.Owner, "Speech",

View File

@@ -97,8 +97,8 @@ namespace OpenRA.Mods.Cnc.Activities
}
// Consume teleport charges if this wasn't triggered via chronosphere
if (teleporter == self && pc != null)
pc.ResetChargeTime();
if (teleporter == self)
pc?.ResetChargeTime();
// Trigger screen desaturate effect
if (screenFlash)

View File

@@ -194,8 +194,7 @@ namespace OpenRA.Mods.Cnc.Graphics
public void RefreshBuffer()
{
if (vertexBuffer != null)
vertexBuffer.Dispose();
vertexBuffer?.Dispose();
vertexBuffer = Game.Renderer.CreateVertexBuffer(totalVertexCount);
vertexBuffer.SetData(vertices.SelectMany(v => v).ToArray(), totalVertexCount);
cachedVertexCount = totalVertexCount;
@@ -234,8 +233,7 @@ namespace OpenRA.Mods.Cnc.Graphics
public void Dispose()
{
if (vertexBuffer != null)
vertexBuffer.Dispose();
vertexBuffer?.Dispose();
sheetBuilder.Dispose();
}
}

View File

@@ -52,13 +52,8 @@ namespace OpenRA.Mods.Cnc.Traits
if (!IsTraitDisabled && damage != null)
{
var damageSubTicks = (int)(damage.Value * 100L * Info.DamageMultiplier / Info.DamageDivisor);
if (spm.Powers.TryGetValue(Info.OrderName, out var spi))
{
var dspi = spi as GrantPrerequisiteChargeDrainPower.DischargeableSupportPowerInstance;
if (dspi != null)
dspi.Discharge(damageSubTicks);
}
(spi as GrantPrerequisiteChargeDrainPower.DischargeableSupportPowerInstance)?.Discharge(damageSubTicks);
}
return 100;

View File

@@ -240,9 +240,7 @@ namespace OpenRA.Mods.Cnc.Traits
new LocationInit(self.Location),
new OwnerInit(self.Owner)
});
var driverMobile = driver.TraitOrDefault<Mobile>();
if (driverMobile != null)
driverMobile.Nudge(driver);
driver.TraitOrDefault<Mobile>()?.Nudge(driver);
}
}
}

View File

@@ -49,8 +49,7 @@ namespace OpenRA.Mods.Cnc.Traits
var external = toActor.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == info.Condition && t.CanGrantCondition(toActor, this));
if (external != null)
external.GrantCondition(toActor, this, duration, remaining);
external?.GrantCondition(toActor, this, duration, remaining);
}
void IConditionTimerWatcher.Update(int duration, int remaining)

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)
{
service.client.UpdateParty(new Party
GetService()?.client.UpdateParty(new Party
{
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);
if (buildingInfo.RequiresBaseProvider)
{
// May be null if the build anywhere cheat is active
// FindBaseProvider may return 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();
}
if (buildingInfo.RequiresBaseProvider)
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;
}

Some files were not shown because too many files have changed in this diff Show More