- Home /
Manged plugins access scripts
https://docs.unity3d.com/Manual/UsingDLL.html
I have followed this guide and everything is working fine.
But, lets say I want to access a custom script/class that is in the unity project. How would I do that?
Thanks!
Answer by Bunny83 · Jun 14, 2017 at 11:47 AM
That's not possible. An assembly (DLL) can only access other assemblies which have to be compiled before in order to be referenced during compilation. All your script files get compiled by Unity into a single assembly (with some exceptions, see below). Any compiled assembly you put into your project will automatically be referenced when Unity compiles your scripts in your project. Therefore the scripts can use / access everything that has been defined in those assemblies.
However since your custom assembly needs to be compiled ahead of time, there's no way for it to access any of the classes you may define in your scripts.
A common way is to provide an interface definition which you compile into a seperate "shared" assembly.
Example:
// inside your common assembly
public interface IPlayer
{
string GetName();
Vector3 GetPosition();
void MoveTo(Vector3 aTarget);
}
public interface IPlugin
{
void Initialize(IPlayer aPlayer);
}
Now your custom assembly can define a class that implements the IPlugin interface. From your game code you can search for all classes that implement that interface, create an instance / attach it to a gameobject and call intitialize on it. That way you can pass the plugin a reference to an IPlayer. Your Player script would implement the IPlayer interface and provide the information that the plugin needs.
The common assembly need to be referenced by your plugin project and need to be copied into your Unity project.
Note that you have to define an interface for everything that your custom DLL should be able to reference. This is commonly known as a "plugin interface". The actual game / Unity project doesn't need to know anything about the plugin. All it knows is how to create an instance of the interface class which is defined in the plugin. At the same time the interface is providing an abstract access to common things in your project which the plugin can use.
That's what I thought. I already did a "plugin interface" but it's to much of a pain.
I was hoping unity would target something higher than .NET 3.5 soon, then maybe I could use better reflection or linq with dynamic, but I am just stuck with what I got. Thanks for the input!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Making a bubble level (not a game but work tool) 1 Answer
Json.net - windows store phone 8.1 2 Answers
How does "build" work? 1 Answer