Acces a script in the editor folder

Say for instance I need to access a function that is in a class in the editor folder like this:

using UnityEngine;
namespace MyNamepace //in Editor folder
{
	public class myClass
	{
		public int Add(int int1, int int2)
		{
			return int1 + int2;
		}
	}
}

script outside of editor folder:

using UnityEngine;
using MyNamespace;
public class Test : MonoBehaviour
{
	public void Awake()
	{
		int1 = 2;
		int2 = 2;
		int result = myClass.Add(int1, int2);
		print(result.ToString());
	}
}

This gives a ‘CS0246: The type or namespace name `MyNamespace’ could not be found’ but it works when MyNamespace is outside of the Editor folder, note that this is just an example script because I dont want to post a 10 line and a 600 line script here. Any ideas?

2 Answers

2

The editor files are compiled last and with a reference to everything else - however the non-editor files do not have a reference to the editor code which is in a separate (and unreferenced) assembly.

So you can’t do that. Whatever needs to be referenced from both needs to be outside the Editor folder.

See that's why I like to hang out on unity answers, teaches me some things that might come in handy in the future. +1

–

The problem with this method is that Unity will undoubtedly have an update in where your names might change? I think.... It happened to me with using reflection at some point, although I can't recall where it was...

–

This is possible with reflection. It obviously breaks encapsulation but I have required it for a resource manager as static constructors in the editor don’t get re-ran on return from play mode.

System.Reflection.Assembly editorAssembly = System.AppDomain.CurrentDomain.GetAssemblies().First( a => a.FullName.StartsWith( "Assembly-CSharp-Editor," ) ); // ',' included to ignore  Assembly-CSharp-Editor-FirstPass
Type utilityType = editorAssembly.GetTypes().FirstOrDefault( t => t.FullName.Contains( "ResManEditorUtility" ) );
utilityType.GetMethod( "InitialiseResMan", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static ).Invoke( obj: null, parameters: null );

I feel I should clarify why breaking encapsulation like this is bad. Any scripts in the Editor folder will not end up in a build. So while this can be done, it won't work in the final build.

–