{"id":17019029,"url":"https://github.com/robert-96/unity-swift","last_synced_at":"2025-04-22T21:46:51.076Z","repository":{"id":184546874,"uuid":"656928593","full_name":"Robert-96/unity-swift","owner":"Robert-96","description":"A simple Unity plug-in for iOS.","archived":false,"fork":false,"pushed_at":"2023-07-29T23:31:41.000Z","size":35,"stargazers_count":24,"open_issues_count":2,"forks_count":8,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-03-29T19:11:17.941Z","etag":null,"topics":["csharp","ios","objective-c","plugin","swift","unity"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Robert-96.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-06-22T00:11:13.000Z","updated_at":"2025-02-25T21:19:22.000Z","dependencies_parsed_at":null,"dependency_job_id":"b312dbd9-0bfc-4a03-b2f8-00205fccd66c","html_url":"https://github.com/Robert-96/unity-swift","commit_stats":null,"previous_names":["robert-96/unity-swift"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Robert-96%2Funity-swift","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Robert-96%2Funity-swift/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Robert-96%2Funity-swift/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Robert-96%2Funity-swift/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Robert-96","download_url":"https://codeload.github.com/Robert-96/unity-swift/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250330942,"owners_count":21413067,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csharp","ios","objective-c","plugin","swift","unity"],"created_at":"2024-10-14T06:47:50.100Z","updated_at":"2025-04-22T21:46:51.055Z","avatar_url":"https://github.com/Robert-96.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# UnitySwift\n\nA simple Unity plug-in for iOS designed to serve as a starting point for creating new plugins that bridge [Unity](http://unity3d.com/) and [Swift](https://swift.org/).\n\n## Getting Started\n\nFollow the instructions below to set up the plugin and integrate it into your Unity project.\n\n### Prerequisites\n\n* Unity 2019.x or later\n* Xcode 11 or later\n\n### Integration into Your Own Project\n\n1. Clone or download this repository.\n1. Open the Unity project where you want to integrate the Swift plugin.\n1. Copy the entire `Assets/Plugins/iOS` folder from this repository into your Unity project's `Assets/Plugins` folder.\n\n## Create a Unity plug-in from scratch\n\n### How to call Swift methods from Unity\n\n#### **Step 1**: Create your Swift classes\n\nAdd the following code into `Assets/Plugins/iOS/SwiftToUnity/Source/SwiftToUnity.swift`:\n\n```swift\nimport Foundation\n\n@objc public class SwiftToUnity: NSObject {\n    @objc public static let shared = SwiftToUnity()\n\n    /// Returns the \"Hello, Swift!\" string.\n    ///\n    /// - Returns: The \"Hello, Swift!\" string.\n    @objc public func swiftHelloWorld() -\u003e String {\n        return \"Hello, Swift!\"\n    }\n}\n```\n\nNote that here `@obc` instructs Swift to make classes or methods available to Objective-C as well as Swift code.\n\n#### **Step 2**: Create a `.mm` bridge file\n\nAdd the following code into `Assets/Plugins/iOS/SwiftToUnity/Source/SwiftToUnityBridge.mm`:\n\n```objc\n#import \u003cUnityFramework/UnityFramework-Swift.h\u003e\n#import \"UnityInterface.h\"\n\nextern \"C\"\n{\n    char* cStringCopy(const char* string) {\n        if (string == NULL) {\n            return NULL;\n        }\n\n        size_t length = strlen(string) + 1;\n        char* res = (char*) malloc(length);\n\n        if (res != NULL) {\n            memcpy(res, string, length);\n        }\n\n        return res;\n    }\n\n    char* cHelloWorld()\n    {\n        NSString *returnString = [[SwiftToUnity shared] swiftHelloWorld];\n        return cStringCopy([returnString UTF8String]);\n    }\n}\n```\n\nThe `SwiftToUnityBridge.mm` file is the bridging medium between Swift and Unity.\n\n#### **Step 3**: Add ``UnityFramework.modulemap``\n\nAdd the following code into `Assets/Plugins/iOS/SwiftToUnity/Source/UnityFramework.modulemap`:\n\n```objc\nframework module UnityFramework {\n  umbrella header \"UnityFramework.h\"\n\n  export *\n  module * { export * }\n\n  module UnityInterface {\n      header \"UnityInterface.h\"\n\n      export *\n  }\n}\n```\n\n#### **Step 4**: Add ``SwiftToUnityPostProcess.cs`` script\n\nFirst, you will need to add the [PostProcessing](https://docs.unity3d.com/2022.3/Documentation/Manual/com.unity.postprocessing.html) package to your Unity project.\n\nTo install the package, go to **Window \u003e Package Manager** and switch the view from **In Project** to **All**. Select **Post Processing** in the list. In the right panel you'll find information about the package and a button to install or update to the latest available version for the version of Unity you are running.\n\nNow add the following code into `Assets/Plugins/iOS/SwiftToUnity/Editor/SwiftToUnityPostProcess.cs`:\n\n```csharp\n#if UNITY_IOS\nusing System.IO;\nusing UnityEngine;\nusing UnityEditor;\nusing UnityEditor.Callbacks;\nusing UnityEditor.iOS.Xcode;\n\npublic static class SwiftToUnityPostProcess\n{\n    [PostProcessBuild]\n    public static void OnPostProcessBuild(BuildTarget buildTarget, string buildPath)\n    {\n        Debug.Log(\"OnPostProcessBuild: \" + buildTarget);\n\n        if (buildTarget == BuildTarget.iOS)\n        {\n            var projectPath = buildPath + \"/Unity-iPhone.xcodeproj/project.pbxproj\";\n\n            var project = new PBXProject();\n            project.ReadFromFile(projectPath);\n\n            var unityFrameworkGuid = project.GetUnityFrameworkTargetGuid();\n\n            // Modulemap\n            project.AddBuildProperty(unityFrameworkGuid, \"DEFINES_MODULE\", \"YES\");\n\n            var moduleFile = buildPath + \"/UnityFramework/UnityFramework.modulemap\";\n            if (!File.Exists(moduleFile))\n            {\n                FileUtil.CopyFileOrDirectory(\"Assets/Plugins/iOS/SwiftToUnity/Source/UnityFramework.modulemap\", moduleFile);\n                project.AddFile(moduleFile, \"UnityFramework/UnityFramework.modulemap\");\n                project.AddBuildProperty(unityFrameworkGuid, \"MODULEMAP_FILE\", \"$(SRCROOT)/UnityFramework/UnityFramework.modulemap\");\n            }\n\n            // Headers\n            string unityInterfaceGuid = project.FindFileGuidByProjectPath(\"Classes/Unity/UnityInterface.h\");\n            project.AddPublicHeaderToBuild(unityFrameworkGuid, unityInterfaceGuid);\n\n            string unityForwardDeclsGuid = project.FindFileGuidByProjectPath(\"Classes/Unity/UnityForwardDecls.h\");\n            project.AddPublicHeaderToBuild(unityFrameworkGuid, unityForwardDeclsGuid);\n\n            string unityRenderingGuid = project.FindFileGuidByProjectPath(\"Classes/Unity/UnityRendering.h\");\n            project.AddPublicHeaderToBuild(unityFrameworkGuid, unityRenderingGuid);\n\n            string unitySharedDeclsGuid = project.FindFileGuidByProjectPath(\"Classes/Unity/UnitySharedDecls.h\");\n            project.AddPublicHeaderToBuild(unityFrameworkGuid, unitySharedDeclsGuid);\n\n            // Save project\n            project.WriteToFile(projectPath);\n        }\n\n        Debug.Log(\"OnPostProcessBuild: Complete\");\n    }\n}\n#endif\n```\n\nBe sure to change the following line in ``SwiftPostProcess.cs`` script with the correct path to your `UnityFramework.modulemap` file:\n\n```csharp\nFileUtil.CopyFileOrDirectory(\"Assets/Plugins/iOS/SwiftToUnity/Source/UnityFramework.modulemap\", moduleFile);\n```\n\n#### **Step 5**: Call your Swift methods from Unity\n\n```csharp\nusing System.Runtime.InteropServices;\nusing UnityEngine;\n\npublic class CanvasScript : MonoBehaviour\n{\n    [DllImport(\"__Internal\")]\n    private static extern string cHelloWorld();\n\n    private void Start()\n    {\n        cHelloWorld();\n    }\n}\n```\n\n### How to call Unity methods from Swift\n\nTo call Unity methods from Swift, use `UnitySendMessage` function like below:\n\n```swift\n// SwiftToUnity.swift\nimport Foundation\n\n@objc public class SwiftToUnity: NSObject {\n    @objc public static let shared = SwiftToUnity()\n\n    /// Sends a \"Hello World\" message to the \"Canvas\" GameObject by calling the \"OnMessageReceived\" script method on that object with the \"Hello World!\" message.\n    @objc public func swiftSendHelloWorldMessage() {\n        // The UnitySendMessage function has three parameters: the name of the target GameObject, the script method to call on that object and the message string to pass to the called method.\n        UnitySendMessage(\"Canvas\", \"OnMessageReceived\", \"Hello World!\");\n    }\n}\n```\n\nSee [SwiftToUnity.swift](Assets/Plugins/iOS/SwiftToUnity/Source/SwiftToUnity.swift).\n\nFor more information about `UnitySendMessage`, check out [Unity's Documentation](https://docs.unity3d.com/Manual/PluginsForIOS.html).\n\n## License\n\nThis project is licensed under the [MIT License](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frobert-96%2Funity-swift","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frobert-96%2Funity-swift","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frobert-96%2Funity-swift/lists"}