在Swift代码中编写Unity IOS插件

Mic*_*l A 5 objective-c unity-game-engine ios swift

是否有可能在Swift中编写统一的IOS插件?

我已经有一个工作的swift框架,并希望将其用作Unity中的插件

我看到一些地方说它只能在Objective-c上完成但是有一个swift的解决方法吗?

Abs*_*akt 8

如何调用 Unity 方法

Unity 接口函数在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)
    }
}
Run Code Online (Sandbox Code Playgroud)

如何从 Unity 访问 Swift 类

第 1 步:创建您的 Swift 类。

//  Example.swift

import Foundation

class Example : NSObject {
    static func swiftMethod(_ message: String) {
        print("\(#function) is called with message: \(message)")
    }
}
Run Code Online (Sandbox Code Playgroud)

第 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]];
    }
}
Run Code Online (Sandbox Code Playgroud)

第 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
    }
}
Run Code Online (Sandbox Code Playgroud)

第 4 步:从 C# 代码中调用该方法。

Example.CallSwiftMethod("Hello, Swift!");
Run Code Online (Sandbox Code Playgroud)

UnitySwift-Bridging-Header.h和 unityswift-Swift.h的文件名在 Build Settings 中的“Objective-C Bridging Header”条目和“Objective-C Generated Interface Header Name”条目中定义。当 Unity 构建运行时,PostProcesser会自动设置有关 Swift 编译器的这些设置和其他设置。

要求

iOS 7 或更高版本

兼容性

统一 5.3.5f1 Xcode 7.3.1

  • @Abs3akt,不幸的是,这个方法不再起作用——只是没有找到“unityswift-Swift.h” (2认同)

Pau*_*Jan 6

由于无法从Unity访问顶级Swift,因此Swift的"解决方法"是围绕它编写Objective-C包装类,并访问.

取决于您的Swift代码的数量和复杂性,这可能仍然是最佳方法.