Useful C# practices

Last modified by Maarten Struijk Wilbrink on 2021/11/08 14:23

Better Practices

You can find some general “Better Practices” here. To recap: make your Project easier to change

Some useful C# practices will be described below. This is not an exhaustive list of how to do things in C#, but can be used as a small overview of concepts which promote code that is ‘easier to change’. 

If you really want to dig deep into creating a sustainable code-base, have a look at the online version of Game Programming Patterns (the examples are in C++).

Singletons

A 'singleton' is a way to make sure there's only 1 instance of a class, and to have that class (and its variables and methods) be globally accessible. The use of singletons is greatly contested, because it has some inherent problems. 

You create a singleton class like so:
public class SingletonExampleClass : MonoBehaviour
{
   public int someInteger;

   private static SingletonExampleClass _instance;

   public static SingletonExampleClass Instance
    {
       get
        {
           return _instance;
        }
    }


   private void Awake()
    {
       if (_instance != null && _instance != this)
        {
            Destroy(this.gameObject);
        }
       else
        {
            _instance = this;
        }
    }

   
   public void InterestingMethod()
    {
       // Do something
   }

   // Rest of your code...
}

The upside of this is that you can easily get a reference to this class from another class, and access any public variables and methods:
public class AnotherClass : MonoBehaviour
{
   private int thisInteger;

   private void GetOtherVariable()
    {
        thisInteger = SingletonExampleClass.Instance.someInteger; // Here you have free access to the integer in the singleton
   }

   private void RunOtherMethod()
    {
        SingletonExampleClass.Instance.InterestingMethod(); // You have free access to the method on the singleton
   }

   // Rest of your code...
}

The downside is that you're now tightly coupling the Singleton class to everything else in your code. If you ever want to make changes to your code (which is likely), you're going to have to change all the references to this singleton class.
Another downside is that you can hardly have two (near) identical classes anymore: the singleton pattern is explicitly designed to make sure this doesn't happen.
Finally, using this many global information makes it hard to reason about bugs: it is hard to find out where they originate, and which aspects of your code are affected by it. 

(Very) simple solutions instead of Singletons

Scriptable Object Variables

Tags:
   
solo
XWiki 14.10.13
contact@xwiki.com