Skip to content

Instantly share code, notes, and snippets.

@troy-lamerton
Last active March 28, 2023 00:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troy-lamerton/6499cb8861596281596f2b3604a03359 to your computer and use it in GitHub Desktop.
Save troy-lamerton/6499cb8861596281596f2b3604a03359 to your computer and use it in GitHub Desktop.
Swift "Hello World" Unity plugin
using System.Runtime.InteropServices;
// Put this C# file anywhere in Assets/
public static class HelloPlugin {
/// Call into swift
#if UNITY_IOS && !UNITY_EDITOR
[DllImport("__Internal", EntryPoint = "LIBHelloWorld")]
public static extern void HelloWorld();
#else
public static void HelloWorld() { }
#endif
}
// Put this Swift file in Assets/Plugins/iOS/
@_cdecl("LIBHelloWorld")
func libHelloWorld() {
// do anything here
print("Hello World!")
}
@troy-lamerton
Copy link
Author

Passing parameters also works well.

While the @_cdecl is undocumented, I use this annotation a lot in production and have no issues to report.

Official support has been proposed in this thread.

@troy-lamerton
Copy link
Author

troy-lamerton commented Feb 24, 2023

Fixed compile error when building for iOS.

If you already have loose swift files building in your Xcode project, it just works.

With an empty unity project you may need to toggle an Xcode build setting so that swift files are built (a few years ago this was required).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment