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> /// </summary>
internal void OnActorDisposeOuter(Actor self) internal void OnActorDisposeOuter(Actor self)
{ {
if (ChildActivity != null) ChildActivity?.OnActorDisposeOuter(self);
ChildActivity.OnActorDisposeOuter(self);
OnActorDispose(self); OnActorDispose(self);
} }
@@ -199,8 +198,7 @@ namespace OpenRA.Activities
if (!IsInterruptible) if (!IsInterruptible)
return; return;
if (ChildActivity != null) ChildActivity?.Cancel(self);
ChildActivity.Cancel(self);
// Directly mark activities that are queued and therefore didn't run yet as done // Directly mark activities that are queued and therefore didn't run yet as done
State = State == ActivityState.Queued ? ActivityState.Done : ActivityState.Canceling; State = State == ActivityState.Queued ? ActivityState.Done : ActivityState.Canceling;
@@ -243,11 +241,9 @@ namespace OpenRA.Activities
Console.WriteLine(GetType().ToString().Split('.').Last()); 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) public override bool Tick(Actor self)
{ {
if (a != null) a(); a?.Invoke();
return true; return true;
} }
} }

View File

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

View File

@@ -90,8 +90,7 @@ namespace OpenRA
public void CancelAsync() public void CancelAsync()
{ {
lock (syncObject) 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) public static object GetValue(string fieldName, Type fieldType, MiniYaml yaml, MemberInfo field)
{ {
var value = yaml.Value; var value = yaml.Value?.Trim();
if (value != null) value = value.Trim();
if (fieldType == typeof(int)) if (fieldType == typeof(int))
{ {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -67,10 +67,7 @@ namespace OpenRA
if (a.FullName == e.Name) if (a.FullName == e.Name)
return a; return a;
if (assemblies == null) return assemblies?.Select(a => a.Assembly).FirstOrDefault(a => a.FullName == e.Name);
return null;
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 // 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(); font.Dispose();
using (new PerfTimer("SpriteFonts")) using (new PerfTimer("SpriteFonts"))
{ {
if (fontSheetBuilder != null) fontSheetBuilder?.Dispose();
fontSheetBuilder.Dispose();
fontSheetBuilder = new SheetBuilder(SheetType.BGRA, 512); fontSheetBuilder = new SheetBuilder(SheetType.BGRA, 512);
Fonts = modData.Manifest.Get<Fonts>().FontList.ToDictionary(x => x.Key, Fonts = modData.Manifest.Get<Fonts>().FontList.ToDictionary(x => x.Key,
x => new SpriteFont(x.Value.Font, modData.DefaultFileSystem.Open(x.Value.Font).ReadAllBytes(), 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 (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 // Render the screen into a frame buffer to simplify reading back screenshots
screenBuffer = Context.CreateFrameBuffer(surfaceBufferSize, Color.FromArgb(0xFF, 0, 0, 0)); screenBuffer = Context.CreateFrameBuffer(surfaceBufferSize, Color.FromArgb(0xFF, 0, 0, 0));
@@ -195,8 +193,7 @@ namespace OpenRA
var worldBufferSize = worldViewport.Size.NextPowerOf2(); var worldBufferSize = worldViewport.Size.NextPowerOf2();
if (worldSprite == null || worldSprite.Sheet.Size != worldBufferSize) 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 // 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); worldBuffer = Context.CreateFrameBuffer(worldBufferSize);
@@ -329,8 +326,7 @@ namespace OpenRA
{ {
if (currentBatchRenderer == value) if (currentBatchRenderer == value)
return; return;
if (currentBatchRenderer != null) currentBatchRenderer?.Flush();
currentBatchRenderer.Flush();
currentBatchRenderer = value; currentBatchRenderer = value;
} }
} }
@@ -460,8 +456,7 @@ namespace OpenRA
{ {
WorldModelRenderer.Dispose(); WorldModelRenderer.Dispose();
tempBuffer.Dispose(); tempBuffer.Dispose();
if (fontSheetBuilder != null) fontSheetBuilder?.Dispose();
fontSheetBuilder.Dispose();
if (Fonts != null) if (Fonts != null)
foreach (var font in Fonts.Values) foreach (var font in Fonts.Values)
font.Dispose(); font.Dispose();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -65,8 +65,7 @@ namespace OpenRA.Mods.Cnc.Activities
t.Infiltrated(targetActor, self, infiltrates.Info.Types); t.Infiltrated(targetActor, self, infiltrates.Info.Types);
var exp = self.Owner.PlayerActor.TraitOrDefault<PlayerExperience>(); 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)) if (!string.IsNullOrEmpty(infiltrates.Info.Notification))
Game.Sound.PlayNotification(self.World.Map.Rules, self.Owner, "Speech", 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 // Consume teleport charges if this wasn't triggered via chronosphere
if (teleporter == self && pc != null) if (teleporter == self)
pc.ResetChargeTime(); pc?.ResetChargeTime();
// Trigger screen desaturate effect // Trigger screen desaturate effect
if (screenFlash) if (screenFlash)

View File

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

View File

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

View File

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

View File

@@ -49,8 +49,7 @@ namespace OpenRA.Mods.Cnc.Traits
var external = toActor.TraitsImplementing<ExternalCondition>() var external = toActor.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == info.Condition && t.CanGrantCondition(toActor, this)); .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) void IConditionTimerWatcher.Update(int duration, int remaining)

View File

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

View File

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

View File

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

View File

@@ -138,9 +138,7 @@ namespace OpenRA.Mods.Common.Activities
QueueChild(move.MoveTo(targetCell, targetLineColor: Color.Green)); QueueChild(move.MoveTo(targetCell, targetLineColor: Color.Green));
var delta = (self.CenterPosition - host.CenterPosition).LengthSquared; var delta = (self.CenterPosition - host.CenterPosition).LengthSquared;
var transport = transportCallers.FirstOrDefault(t => t.MinimumDistance.LengthSquared < delta); transportCallers.FirstOrDefault(t => t.MinimumDistance.LengthSquared < delta)?.RequestTransport(self, targetCell);
if (transport != null)
transport.RequestTransport(self, targetCell);
return false; return false;
} }
@@ -261,11 +259,7 @@ namespace OpenRA.Mods.Common.Activities
if (health.DamageState == DamageState.Undamaged) if (health.DamageState == DamageState.Undamaged)
{ {
if (host.Actor.Owner != self.Owner) if (host.Actor.Owner != self.Owner)
{ host.Actor.Owner.PlayerActor.TraitOrDefault<PlayerExperience>()?.GiveExperience(repairsUnits.Info.PlayerExperience);
var exp = host.Actor.Owner.PlayerActor.TraitOrDefault<PlayerExperience>();
if (exp != null)
exp.GiveExperience(repairsUnits.Info.PlayerExperience);
}
Game.Sound.PlayNotification(self.World.Map.Rules, self.Owner, "Speech", repairsUnits.Info.FinishRepairingNotification, self.Owner.Faction.InternalName); 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); askedColor.ToAhsv(out _, out _, out var s, out var v);
if (s < HsvSaturationRange[0] || s > HsvSaturationRange[1] || v < HsvValueRange[0] || v > HsvValueRange[1]) 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; forbiddenColor = askedColor;
return false; return false;
} }
@@ -69,16 +68,14 @@ namespace OpenRA.Mods.Common
// Validate color against the current map tileset // Validate color against the current map tileset
if (!IsValid(askedColor, terrainColors, out forbiddenColor)) 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; return false;
} }
// Validate color against other clients // Validate color against other clients
if (!IsValid(askedColor, playerColors, out forbiddenColor)) 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; 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) public static void UpdateStatus(DiscordState state, string details = null, string secret = null, int? players = null, int? slots = null)
{ {
var service = GetService(); GetService()?.SetStatus(state, details, secret, players, slots);
if (service != null)
service.SetStatus(state, details, secret, players, slots);
} }
public static void SetPlayers(int players, int slots) public static void SetPlayers(int players, int slots)
{ {
var service = GetService(); GetService()?.client.UpdateParty(new Party
if (service != null)
{ {
service.client.UpdateParty(new Party ID = Secrets.CreateFriendlySecret(new Random()),
{ Size = players,
ID = Secrets.CreateFriendlySecret(new Random()), Max = slots
Size = players, });
Max = slots
});
}
} }
public static void UpdatePlayers(int players, int slots) public static void UpdatePlayers(int players, int slots)
{ {
var service = GetService(); GetService()?.client.UpdatePartySize(players, slots);
if (service != null)
service.client.UpdatePartySize(players, slots);
} }
public static void UpdateDetails(string details) public static void UpdateDetails(string details)
{ {
var service = GetService(); GetService()?.client.UpdateDetails(details);
if (service != null)
service.client.UpdateDetails(details);
} }
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -197,8 +197,7 @@ namespace OpenRA.Mods.Common.Projectiles
public void Tick(World world) public void Tick(World world)
{ {
if (anim != null) anim?.Tick();
anim.Tick();
lastPos = pos; lastPos = pos;
pos = WPos.LerpQuadratic(source, target, angle, ticks, length); 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); args.Weapon.Impact(Target.FromPos(pos), warheadArgs);
} }
if (anim != null) anim?.Tick();
anim.Tick();
} }
public IEnumerable<IRenderable> Render(WorldRenderer wr) public IEnumerable<IRenderable> Render(WorldRenderer wr)

View File

@@ -792,8 +792,7 @@ namespace OpenRA.Mods.Common.Projectiles
public void Tick(World world) public void Tick(World world)
{ {
ticks++; ticks++;
if (anim != null) anim?.Tick();
anim.Tick();
// Switch from freefall mode to homing mode // Switch from freefall mode to homing mode
if (ticks == info.HomingActivationDelay + 1) 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) if (ticks++ > info.Duration && animationComplete)
world.AddFrameEndTask(w => w.Remove(this)); world.AddFrameEndTask(w => w.Remove(this));

View File

@@ -31,8 +31,7 @@ namespace OpenRA.Mods.Common.Activities
{ {
try try
{ {
if (function != null) function?.Call().Dispose();
function.Call().Dispose();
} }
catch (Exception ex) 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.")] [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) 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) if (disposed)
return; return;
if (context != null) context?.Dispose();
context.Dispose();
disposed = true; disposed = true;
} }

View File

@@ -172,10 +172,7 @@ namespace OpenRA.Mods.Common.Scripting
{ {
get get
{ {
if (autotarget == null) return autotarget?.Stance.ToString();
return null;
return autotarget.Stance.ToString();
} }
set set
@@ -197,10 +194,8 @@ namespace OpenRA.Mods.Common.Scripting
get get
{ {
var tooltip = tooltips.FirstEnabledTraitOrDefault(); 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) public void GameEnded(S server)
{ {
if (LanGameBeacon != null) LanGameBeacon?.Stop();
LanGameBeacon.Stop();
lastChanged = Game.RunTime; lastChanged = Game.RunTime;
} }

View File

@@ -18,8 +18,7 @@ namespace OpenRA.Mods.Common.Traits.BotModules.Squads
public void Update(Squad squad) public void Update(Squad squad)
{ {
if (currentState != null) currentState?.Tick(squad);
currentState.Tick(squad);
} }
public void ChangeState(Squad squad, IState newState, bool rememberPrevious) public void ChangeState(Squad squad, IState newState, bool rememberPrevious)
@@ -27,14 +26,12 @@ namespace OpenRA.Mods.Common.Traits.BotModules.Squads
if (rememberPrevious) if (rememberPrevious)
previousState = currentState; previousState = currentState;
if (currentState != null) currentState?.Deactivate(squad);
currentState.Deactivate(squad);
if (newState != null) if (newState != null)
currentState = newState; currentState = newState;
if (currentState != null) currentState?.Activate(squad);
currentState.Activate(squad);
} }
public void RevertToPreviousState(Squad squad, bool saveCurrentState) 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, // If this bridge repair operation connects two pathfinding domains,
// update the domain index. // update the domain index.
var domainIndex = self.World.WorldActor.TraitOrDefault<DomainIndex>(); 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) if (LongBridgeSegmentIsDead() && !killedUnits)
{ {

View File

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

View File

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

View File

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

View File

@@ -131,8 +131,8 @@ namespace OpenRA.Mods.Common.Traits
// Manually manage the inner activity queue // Manually manage the inner activity queue
var activity = currentTransform ?? transform.GetTransformActivity(self); var activity = currentTransform ?? transform.GetTransformActivity(self);
if (!order.Queued && activity.NextActivity != null) if (!order.Queued)
activity.NextActivity.Cancel(self); activity.NextActivity?.Cancel(self);
activity.Queue(new IssueOrderAfterTransform(order.OrderString, order.Target, Color.Green)); 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 // Manually manage the inner activity queue
var activity = currentTransform ?? transform.GetTransformActivity(self); var activity = currentTransform ?? transform.GetTransformActivity(self);
if (!order.Queued && activity.NextActivity != null) if (!order.Queued)
activity.NextActivity.Cancel(self); activity.NextActivity?.Cancel(self);
activity.Queue(new IssueOrderAfterTransform(order.OrderString, order.Target, Color.Green)); 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 // Manually manage the inner activity queue
var activity = currentTransform ?? transform.GetTransformActivity(self); var activity = currentTransform ?? transform.GetTransformActivity(self);
if (!order.Queued && activity.NextActivity != null) if (!order.Queued)
activity.NextActivity.Cancel(self); activity.NextActivity?.Cancel(self);
activity.Queue(new IssueOrderAfterTransform("Move", order.Target, Color.Green)); 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 // Manually manage the inner activity queue
var activity = currentTransform ?? transform.GetTransformActivity(self); var activity = currentTransform ?? transform.GetTransformActivity(self);
if (!order.Queued && activity.NextActivity != null) if (!order.Queued)
activity.NextActivity.Cancel(self); activity.NextActivity?.Cancel(self);
activity.Queue(new IssueOrderAfterTransform(order.OrderString, order.Target, Color.Green)); 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 // Manually manage the inner activity queue
var activity = currentTransform ?? transform.GetTransformActivity(self); var activity = currentTransform ?? transform.GetTransformActivity(self);
if (!order.Queued && activity.NextActivity != null) if (!order.Queued)
activity.NextActivity.Cancel(self); activity.NextActivity?.Cancel(self);
activity.Queue(new IssueOrderAfterTransform(order.OrderString, order.Target, Color.Green)); 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) if (!order.Queued || currentTransform == null)
return; return;
if (!order.Queued && currentTransform.NextActivity != null) if (!order.Queued)
currentTransform.NextActivity.Cancel(self); currentTransform.NextActivity?.Cancel(self);
currentTransform.Queue(new IssueOrderAfterTransform("DeployTransform", order.Target, Color.Green)); 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) void INotifyCrushed.OnCrush(Actor self, Actor crusher, BitSet<CrushClass> crushClasses)
{ {
var external = crusher.TraitsImplementing<ExternalCondition>() crusher.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == Info.OnCrushCondition && t.CanGrantCondition(crusher, self)); .FirstOrDefault(t => t.Info.Condition == Info.OnCrushCondition && t.CanGrantCondition(crusher, self))
?.GrantCondition(crusher, self, Info.OnCrushDuration);
if (external != null)
external.GrantCondition(crusher, self, Info.OnCrushDuration);
} }
void INotifyCrushed.WarnCrush(Actor self, Actor crusher, BitSet<CrushClass> crushClasses) void INotifyCrushed.WarnCrush(Actor self, Actor crusher, BitSet<CrushClass> crushClasses)
{ {
var external = crusher.TraitsImplementing<ExternalCondition>() crusher.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == Info.WarnCrushCondition && t.CanGrantCondition(crusher, self)); .FirstOrDefault(t => t.Info.Condition == Info.WarnCrushCondition && t.CanGrantCondition(crusher, self))
?.GrantCondition(crusher, self, Info.WarnCrushDuration);
if (external != null)
external.GrantCondition(crusher, self, Info.WarnCrushDuration);
} }
} }
} }

View File

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

View File

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

View File

@@ -72,9 +72,7 @@ namespace OpenRA.Mods.Common.Traits
var recipient = actor; // loop variable in closure hazard var recipient = actor; // loop variable in closure hazard
recipient.World.AddFrameEndTask(w => recipient.World.AddFrameEndTask(w =>
{ {
var gainsExperience = recipient.TraitOrDefault<GainsExperience>(); recipient.TraitOrDefault<GainsExperience>()?.GiveLevels(info.Levels);
if (gainsExperience != null)
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); var pilot = self.World.CreateActor(true, Info.PilotActor.ToLowerInvariant(), td);
if (!inAir) if (!inAir)
{ pilot.TraitOrDefault<Mobile>()?.Nudge(pilot);
var pilotMobile = pilot.TraitOrDefault<Mobile>();
if (pilotMobile != null)
pilotMobile.Nudge(pilot);
}
else else
Game.Sound.Play(SoundType.World, Info.ChuteSound, cp); 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)); killer.GiveExperience(Util.ApplyPercentageModifiers(exp, killerExperienceModifier));
} }
var attackerExp = e.Attacker.Owner.PlayerActor.TraitOrDefault<PlayerExperience>(); e.Attacker.Owner.PlayerActor.TraitOrDefault<PlayerExperience>()
if (attackerExp != null) ?.GiveExperience(Util.ApplyPercentageModifiers(exp, new[] { info.PlayerExperienceModifier }));
attackerExp.GiveExperience(Util.ApplyPercentageModifiers(exp, new[] { info.PlayerExperienceModifier }));
} }
} }
} }

View File

@@ -26,9 +26,7 @@ namespace OpenRA.Mods.Common.Traits
if (!building.AppearsFriendlyTo(self)) if (!building.AppearsFriendlyTo(self))
return; return;
var rb = building.TraitOrDefault<RepairableBuilding>(); building.TraitOrDefault<RepairableBuilding>()?.RepairBuilding(building, self.Owner);
if (rb != null)
rb.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) if (p != self.Owner && p.IsAlliedWith(self.Owner) && p != e.Attacker.Owner)
Game.Sound.PlayNotification(rules, p, "Speech", info.AllyNotification, p.Faction.InternalName); 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; lastAttackTime = self.World.WorldTick;

View File

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

View File

@@ -170,8 +170,7 @@ namespace OpenRA.Mods.Common.Traits
foreach (var t in buildingInfo.Tiles(targetLocation)) foreach (var t in buildingInfo.Tiles(targetLocation))
{ {
var host = buildingInfluence.GetBuildingAt(t); 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); 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) if (buildingInfo.RequiresBaseProvider)
{ buildingInfo.FindBaseProvider(w, self.Owner, targetLocation)?.BeginCooldown();
// 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();
}
if (GetNumBuildables(self.Owner) > prevItems) if (GetNumBuildables(self.Owner) > prevItems)
triggerNotification = true; triggerNotification = true;

View File

@@ -61,8 +61,7 @@ namespace OpenRA.Mods.Common.Traits
{ {
terrainColor[uv] = GetColor(world.Map, uv); terrainColor[uv] = GetColor(world.Map, uv);
if (CellTerrainColorChanged != null) CellTerrainColorChanged?.Invoke(uv);
CellTerrainColorChanged(uv);
} }
public void WorldLoaded(World w, WorldRenderer wr) 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) protected void PauseProduction(string itemName, bool paused)
{ {
var item = Queue.FirstOrDefault(a => a.Item == itemName); Queue.FirstOrDefault(a => a.Item == itemName)?.Pause(paused);
if (item != null)
item.Pause(paused);
} }
protected void CancelProduction(string itemName, uint numberToCancel) protected void CancelProduction(string itemName, uint numberToCancel)
@@ -646,8 +644,7 @@ namespace OpenRA.Mods.Common.Traits
if (Done) if (Done)
{ {
if (OnComplete != null) OnComplete?.Invoke();
OnComplete();
return; return;
} }

View File

@@ -105,14 +105,11 @@ namespace OpenRA.Mods.Common.Traits.Render
{ {
Reverse(self, () => Reverse(self, () =>
{ {
var wsb = wsbs.FirstEnabledTraitOrDefault();
// HACK: The actor remains alive and active for one tick before the followup activity // 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 // (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. // 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! // These workarounds will break the actor if the followup activity doesn't dispose it!
if (wsb != null) wsbs.FirstEnabledTraitOrDefault()?.DefaultAnimation.PlayFetchIndex(info.Sequence, () => 0);
wsb.DefaultAnimation.PlayFetchIndex(info.Sequence, () => 0);
token = self.GrantCondition(info.Condition); token = self.GrantCondition(info.Condition);

View File

@@ -159,8 +159,7 @@ namespace OpenRA.Mods.Common.Traits.Render
void ITick.Tick(Actor self) void ITick.Tick(Actor self)
{ {
if (shadow != null) shadow?.Tick();
shadow.Tick();
} }
IEnumerable<IRenderable> IRender.Render(Actor self, WorldRenderer wr) 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), () => DefaultAnimation.PlayThen(NormalizeSequence(self, name), () =>
{ {
CancelCustomAnimation(self); CancelCustomAnimation(self);
if (after != null) after?.Invoke();
after();
}); });
} }
@@ -112,8 +111,7 @@ namespace OpenRA.Mods.Common.Traits.Render
DefaultAnimation.PlayBackwardsThen(NormalizeSequence(self, name), () => DefaultAnimation.PlayBackwardsThen(NormalizeSequence(self, name), () =>
{ {
CancelCustomAnimation(self); CancelCustomAnimation(self);
if (after != null) after?.Invoke();
after();
}); });
} }

View File

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

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); Game.Sound.PlayNotification(self.World.Map.Rules, discoverer, "Speech", Info.Notification, discoverer.Faction.InternalName);
// Radar notification // Radar notification
if (Info.PingRadar && radarPings.Value != null) if (Info.PingRadar)
radarPings.Value.Add(() => true, self.CenterPosition, Color.Red, 50); 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); Game.Sound.Play(SoundType.World, info.OnFireSound, order.Target.CenterPosition);
foreach (var a in UnitsInRange(self.World.Map.CellContaining(order.Target.CenterPosition))) foreach (var a in UnitsInRange(self.World.Map.CellContaining(order.Target.CenterPosition)))
{ a.TraitsImplementing<ExternalCondition>()
var external = a.TraitsImplementing<ExternalCondition>() .FirstOrDefault(t => t.Info.Condition == info.Condition && t.CanGrantCondition(a, self))
.FirstOrDefault(t => t.Info.Condition == info.Condition && t.CanGrantCondition(a, self)); ?.GrantCondition(a, self, info.Duration);
if (external != null)
external.GrantCondition(a, self, info.Duration);
}
} }
public IEnumerable<Actor> UnitsInRange(CPos xy) public IEnumerable<Actor> UnitsInRange(CPos xy)

View File

@@ -227,10 +227,8 @@ namespace OpenRA.Mods.Common.Traits
return; return;
var power = Instances.FirstOrDefault(i => !i.IsTraitPaused); 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) public virtual void Activate(Order order)

View File

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

View File

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

View File

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

View File

@@ -158,8 +158,7 @@ namespace OpenRA.Mods.Common.Traits
cell.Density = Math.Min(cell.Type.Info.MaxDensity, cell.Density + n); cell.Density = Math.Min(cell.Type.Info.MaxDensity, cell.Density + n);
Content[p] = cell; Content[p] = cell;
if (CellChanged != null) CellChanged?.Invoke(p, cell.Type);
CellChanged(p, cell.Type);
} }
public bool IsFull(CPos cell) public bool IsFull(CPos cell)
@@ -183,8 +182,7 @@ namespace OpenRA.Mods.Common.Traits
else else
Content[cell] = c; Content[cell] = c;
if (CellChanged != null) CellChanged?.Invoke(cell, c.Type);
CellChanged(cell, c.Type);
return c.Type; return c.Type;
} }
@@ -202,8 +200,7 @@ namespace OpenRA.Mods.Common.Traits
Content[cell] = ResourceLayerContents.Empty; Content[cell] = ResourceLayerContents.Empty;
world.Map.CustomTerrain[cell] = byte.MaxValue; world.Map.CustomTerrain[cell] = byte.MaxValue;
if (CellChanged != null) CellChanged?.Invoke(cell, c.Type);
CellChanged(cell, c.Type);
} }
public ResourceType GetResourceType(CPos cell) { return Content[cell].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) foreach (var sequence in sequenceNode.Value.Nodes)
{ {
var facingFudgeNode = sequence.LastChildMatching("UseClassicFacingFudge"); var facingFudgeNode = sequence.LastChildMatching("UseClassicFacingFudge");
if (facingFudgeNode != null) facingFudgeNode?.RenameKey("UseClassicFacings");
facingFudgeNode.RenameKey("UseClassicFacings");
} }
yield break; yield break;

View File

@@ -263,8 +263,7 @@ namespace OpenRA.Mods.Common.UpdateRules
public static void Save(this YamlFileSet files) public static void Save(this YamlFileSet files)
{ {
foreach (var file in 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> /// <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)) if (!IsValidAgainst(a, firedBy))
continue; continue;
var external = a.TraitsImplementing<ExternalCondition>() a.TraitsImplementing<ExternalCondition>()
.FirstOrDefault(t => t.Info.Condition == Condition && t.CanGrantCondition(a, firedBy)); .FirstOrDefault(t => t.Info.Condition == Condition && t.CanGrantCondition(a, firedBy))
?.GrantCondition(a, firedBy, Duration);
if (external != null)
external.GrantCondition(a, firedBy, Duration);
} }
} }
} }

View File

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

View File

@@ -129,9 +129,7 @@ namespace OpenRA.Mods.Common.Widgets
oldBounds.Height); oldBounds.Height);
panelRoot.AddChild(panel); panelRoot.AddChild(panel);
var scrollPanel = panel as ScrollPanelWidget; (panel as ScrollPanelWidget)?.ScrollToSelectedItem();
if (scrollPanel != null)
scrollPanel.ScrollToSelectedItem();
} }
public void ShowDropDown<T>(string panelTemplate, int maxHeight, IEnumerable<T> options, Func<T, ScrollItemWidget, ScrollItemWidget> setupItem) 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 ClearBrush() { SetBrush(null); }
public void SetBrush(IEditorBrush brush) public void SetBrush(IEditorBrush brush)
{ {
if (CurrentBrush != null) CurrentBrush?.Dispose();
CurrentBrush.Dispose();
CurrentBrush = brush ?? DefaultBrush; CurrentBrush = brush ?? DefaultBrush;
} }

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