So I want to make an extension to the Unity gui via C# extension functions.
I am going
static public bool SlideToggle(this GUI gui)
{
return true;
}
However when I then do:
GUI.SlideToggle()
which it autocompletes that.
It gives the error:
Assets/Scripts/ProductView/ProductViewGUIControl.cs(97,21): error CS0117: UnityEngine.GUI' does not contain a definition for SlideToggle’
How do I make an extension class for UnityEngine.GUI???
You can’t extend GUI, GUILayout, EditorGUI, or EditorGUILayout in this way.
From the MSDN page on Extension Methods:
This means that you can’t add static methods to classes. The GUI classes only use static methods. You will see the autocomplete/intellisense correctly if you create an instance of GUI, but it would be the only method you could access.
GUI.SlideToggle() // will not work.
GUI myGUI = new GUI();
myGUI.SlideToggle(); // Will work, but it's weird to use GUI this way.
You should create your own GUI container class. This will allow you to separate controls and keep things organized.
C#
public static class MyGUI
{
public static bool SlideToggle(bool value)
{
// Handle Slide Toggle control here.
}
}
Right. As Eddy said, you should keep your (static) GUI methods within your namespace.
Extension methods are a syntactic sugar that should be avoided, because you have no guarantee that other component author won’t decide to use the same name when extending some class, so you have clashes!