Do you have some app logic or game logic that you want to keep in a separate project? Perhaps you want to re-use your utility functions in your next project and keep them separated from your main project. After reading this tutorial, you are able to use Visual Studio to create a .NET class library and use it from Unity3D.
Create a .NET class library with Unity3D and Visual Studio.
Create a new Unity3D project. Call it LibTest
Save the main scene as ‘main’
Open the Player settings and find the Other settings, Configuration section.
Change the Scripting Runtime to .NET 4.6 (Unity might restart)
Create an empty GameObject and rename it to app
With app selected, click Add Component in the inspector.
Select New Script and call it App
Doubleclick ‘App’ to open in Visual Studio
Rightclick the solution and add a new Project
Select Windows classic desktop and Class library (.NET Framework)
Name the project LibTest.Core
Enter the location of your Unity project.
Click OK.
Rename Class1 to Game
Replace the generated code with:
namespace LibTest.Core
{
public class Game
{
private int _livesLeft = 3;
public bool IsGameOver => _livesLeft == 0;
}
}
Rightclick LibTest.Core and click Properties
Here you see the assembly name and the target framework:
Select Build
Enter ..\assets in the Output path
Press CTRL+SHIFT+B to build the solution
Go back to Unity and the library shows up in the Project tab:
Switch back to Visual Studio
Open App.cs and replace the code with:
using LibTest.Core;
using UnityEngine;
public class App : MonoBehaviour
{
private Game _game = new Game();
private void Update()
{
if (_game.IsGameOver)
{
}
else
{
}
}
}
And that’s it. You can now add stuff to your Game class and access it from the main project.
Written by Loek van den Ouweland on 2017-11-24.
Questions regarding this artice? You can send them to the address below.