是否可以在 Swift 中编写 unity IOS 插件?
我已经有了一个可以工作的 swift 框架,想将它用作 Unity 中的插件
我看到一些地方说它只能在 Objective-c 上完成,但是有没有 swift 的解决方法?
最佳答案
如何调用Unity方法
Unity 接口(interface)函数定义在Unity 构建的Xcode 项目的UnityInterface.h 中。此头文件导入到 UnitySwift-Bridging-Header.h 中,因此您可以直接在 Swift 代码中调用这些函数。
要调用 Unity 方法,请使用 UnitySendMessage
函数,如下所示:
// Example.swift
import Foundation
class Example : NSObject {
static func callUnityMethod(_ message: String) {
// Call a method on a specified GameObject.
UnitySendMessage("CallbackTarget", "OnCallFromSwift", message)
}
}
如何从 Unity 访问 Swift 类
第 1 步:创建您的 Swift 类。
// Example.swift
import Foundation
class Example : NSObject {
static func swiftMethod(_ message: String) {
print("\(#function) is called with message: \(message)")
}
}
第 2 步:包含“unityswift-Swift.h”并定义 C 函数以将 Swift 类包装在 .mm 文件 (Objective-C++) 中。
// Example.mm
#import <Foundation/Foundation.h>
#import "unityswift-Swift.h" // Required
// This header file is generated automatically when Xcode build runs.
extern "C" {
void _ex_callSwiftMethod(const char *message) {
// You can access Swift classes directly here.
[Example swiftMethod:[NSString stringWithUTF8String:message]];
}
}
第 3 步:创建接口(interface)类以从 C# 调用导出的 C 函数。
// Example.cs
using System.Runtime.InteropServices;
public class Example {
#if UNITY_IOS && !UNITY_EDITOR
[DllImport("__Internal")]
private static extern void _ex_callSwiftMethod(string message);
#endif
// Use this method to call Example.swiftMethod() in Example.swift
// from other C# classes.
public static void CallSwiftMethod(string message) {
#if UNITY_IOS && !UNITY_EDITOR
_ex_callSwiftMethod(message);
#endif
}
}
第 4 步:从您的 C# 代码调用该方法。
Example.CallSwiftMethod("Hello, Swift!");
UnitySwift-Bridging-Header.h 和 unityswift-Swift.h 的文件名定义在“Objective-C Bridging Header”条目和“Objective-C Generated Interface Header Name”条目中build设置。这些设置和有关 Swift 编译器的其他设置由 PostProcesser 自动设置当 Unity 构建运行时。
要求
iOS 7 or later
兼容性
Unity 5.3.5f1 Xcode 7.3.1
关于ios - 用 Swift 代码编写 Unity IOS 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31636408/