How to use private classes and functions for testing/debugging in Unity?

Learn how to use Assembly Definition Files and Internals to test and debug your own code without having to make everything public!

Cases where this is useful:

  • You have a Unit Test assembly file that uses another assembly. But the classes or methods you want to test are private and you don't want to make them public.
  • You have a test/debug component that draws stuff from another component or class and those are not public but you don't need them public just for testing purposes.

So, it's basically for testing and debugging purposes, nothing to be going to the standalone or final app.

Easy!  It is good practice just for these cases, since c# has no "friend" clases like c++.

  • ClassA contains private methods and members that you want to access.  ClassA.cs  is the file containing it.
  • ClassB wants to access ClassA "internal" methods and members.

You will need to work with assembly definition files. If you don't know what they are, have a look: https://docs.unity3d.com/Manual/ScriptCompilationAssemblyDefinitionFiles.html

You need one for the A code, and another one containing B code. I recommend using these files to make your code independent from other code in the project. Others will have to add an assembly def too, and add a reference to yours in it.

Basically, anywhere the assembly file is, it contains everything inside that folder and the folders underneath in the hierarchy. If another assembly file is found in the hierarchy, then the current assembly ignores that folder. A new assembly is created from there just for that folder in particular.

AssemblyClassA is the assembly where ClassA is. 

Follow these steps:

  • Add an "AssemblyInfo.cs" empty c# file next to your assembly definition file AssemblyClassA, with the following content:
    using System.Runtime.CompilerServices;
    [assembly: InternalsVisibleTo("AssemblyClassB")]
    • Where "public" would go, before the return keyword in your method, or member, write "internal".  If you have "private" you can change it to "internal".
      internal Vector3 velocity;
      internal void PrivateMethod() {...}
      • Select the assembly definition file in AssemblyClassB and under Assembly Definition References, add the AssemblyClassA definition file. This tells assembly B that it is using A.

      Hope this little trick helped. Now you can use those internal variables and methods directly in your B code.