InfinityExtensions.cs

v4.0

These are extension methods. If you're unsure what they are or how to use them, ask ChatGPT 😍

Is() and IsNot()

This will allow you to compare any value with another and return a true or false based on Is() or IsNot() -- if they are or are not the same value.

public static bool Is<T>(this T value, T compareValue) 
public static bool IsNot<T>(this T value, T compareValue)

// Example
var userInputGatePhrase = "Open the Gate";
if (gate.passPhrase.Is(userInputGatePhrase))
    OpenTheGate();
else
    KillThePlayer(); // Harsh, but that's the rules of the game!

TakeRandom(), TakeRandomIndex(), and TakeRandomAndIndex()

These extend a List<T> and return either an item from the list, the int index of an item from the list, or both!

public static T TakeRandom<T>(this List<T> list)
public static int TakeRandomIndex<T>(this List<T> list)
public static (T, int) TakeRandomAndIndex<T>(this List<T> list)

// Example
var newName = names.TakeRandom();

var randomName = names.TakeRandomAndIndex();
player.Name = newName.Item1;
player.NameIndex = newName.Item2;

Shuffle()

Shuffles a list using the Fisher-Yates shuffle. Optionally providing a startIndex greater than 0, and only the values from that point on will be shuffled, retaining the order of the first group.

public static void Shuffle<T>(this List<T> list
    , int startOrEndIndex = 0, bool fromEnd = false)

// Example
listToShuffle.Shuffle(1); // Shuffles the list directly, but keep the first item.
listToShuffle.Shuffle(2, true); // Shuffles, but keeps the last TWO items in the list

Reverse()

Reverses the order of a list. Optionally provide a startIndex, and only the items from that index on will be reversed.

public static void Reverse<T>(this List<T> list, int startIndex = 0)

// Example
navigationPoints.Reverse(); // reverse the navigation points in the list

AddDistinct()

If the list does not already contain the item to be added, it will be added, and true will be returned. If it already contains the item, then false will be returned.

public static bool AddDistinct<T>(this List<T> list, T item)

// Example
var addedTheItem = listOfItems.AddDistinct(newItem);

// In this example, we don't utilize the return value, but we can be confident that
// the item will only be added if it doesn't already exist.
listOfDistinctItems.AddDistinct(anotherItem);

RoundToDecimal

If the list does not already contain the item to be added, it will be added, and true will be returned. If it already contains the item, then false will be returned.

public static float RoundToDecimal(this float value, int decimals = 2)  

// Example
_text.text = $"{value.RoundToDecimal(2)}"; // Would turn 3.23234 to 3.23

Last updated