Let's take a look at extensions in practice by adding a custom method to the String class.
Create a new C# script in the Scripts folder, name it CustomExtensions, and add the following code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 1
namespace CustomExtensions
{
// 2
public static class StringExtensions
{
// 3
public static void FancyDebug(this string str)
{
// 4
Debug.LogFormat("This string contains {0} characters.",
str.Length);
}
}
}
Let's break down the code:
- First, it declares a namespace named CustomExtensions to hold all the extension classes and methods.
- Then, it declares a static class named StringExtensions for organizational purposes; each group of class extensions should follow this setup.
- Next, it adds a static method named FancyDebug to the StringExtensions...