Skip to content

Commit

Permalink
fix: modify GetOrAddComponent to use TryGetComponent.
Browse files Browse the repository at this point in the history
Null-coalescing operators do not work properly on Unity objects.

See: https://stackoverflow.com/q/76294124
  • Loading branch information
redseiko committed Sep 16, 2023
1 parent 992ff7e commit ea5715a
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions JotunnLib/Extensions/GameObjectExtension.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Reflection;
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;

Expand Down Expand Up @@ -39,7 +39,7 @@ public static T OrNull<T>(this T @this) where T : Object
/// <returns>Component</returns>
public static T GetOrAddComponent<T>(this GameObject gameObject) where T : Component
{
return gameObject.GetComponent<T>() ?? gameObject.AddComponent<T>();
return gameObject.TryGetComponent(out T component) ? component : gameObject.AddComponent<T>();
}

/// <summary>
Expand Down

0 comments on commit ea5715a

Please sign in to comment.