是否可以用Swift编写统一IOS插件?
我已经有了一个有效的、快速的框架,并希望将它作为一个统一插件使用
我看到一些地方说它只能在目标-c上完成,但是有解决办法吗?
发布于 2017-11-24 15:21:00
如何调用统一方法
统一接口函数在UnityInterface.h中定义为UnityInterface.h。此头文件是在UnitySwift-桥接-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:包含“unitySwiver-Swift.h”,并定义C函数将Swift类包装在.mm文件中(目标-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:创建接口类,从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-桥接-Header.h和unitySwi-Swift.h的文件名在构建设置中的“Objective桥接标题”条目和“Objective生成的接口标题名称”中定义。这些设置和有关Swift编译器的其他设置是由PostProcesser在运行Unity时自动设置的。
Requirements
iOS 7或更高版本
Compatibility
统一5.3.5f1 Xcode 7.3.1
发布于 2015-07-26 12:26:43
由于顶级Swift是根本无法从联合访问的,Swift的“解决办法”是围绕它编写一个Objective包装器类,并访问它。
取决于Swift代码的数量和复杂性,这可能仍然是最优的方法。
https://stackoverflow.com/questions/31636408
复制相似问题