Wednesday, April 24, 2024
HomeProgrammingSetting Up iOS Framework for Unity | by Max Kalik | Oct,...

Setting Up iOS Framework for Unity | by Max Kalik | Oct, 2022


From Swift to C#

picture by writer

I gained’t waste your time on a protracted introduction concerning the applied sciences that I’ll describe right here. You almost certainly already work as an iOS Engineer or Sport Developer, which implies you most likely have some questions concerning the subject of this text. So, let’s get began.

This text is cut up into two components. Within the first half, you’ll learn to launch a easy UIViewController from Unity. We’ll drive C# to know Swift. Within the second half, we are going to attempt to develop the utilization of Swift in Unity and discover the constraints.

All proper, right here we go.

Stipulations

  • macOS Monterey
  • XCode 13 (or 14)
  • Unity LTS 2021.3
  • iOS Machine (with no less than iOS14 or increased)

iOS Framework

Open XCode and create a brand new Swift mission — framework.

Swift mission — framework

The identify of the mission is as much as you, I named it SwiftCodeKit. It’s going to be a easy framework with one view controller. We want solely three recordsdata:

In SwiftCodeKitViewController, let’s create a easy UIViewController — with a button on the middle of the view.

SwiftCodeKitViewController.swift

In SwiftCodeKit.swift we are going to gather all our public strategies. Having this public class will assist you to check your framework in iOS tasks. The primary one will probably bebegin(). This methodology presents our SwiftCodeKitViewController.

SwiftCodeKit.swift

The third file SwiftCodeKitBridging.swift will comprise an inventory of public uncovered strategies with C declaration notation @_cdecl. These strategies needs to be saved solely in a non-local scope. First, let’s create a way: startSwiftCodeKitController().

SwiftCodeKitBridging.swift

The attribute @_cdecl is just not documented. For now, you solely must know that this attribute exposes a Swift perform to C. Additional, we are going to experiment a bit bit with this attribute and can determine the limitation.

Constructing framework

In your Xcode mission standing of the toolbar select Any iOS Machine (arm64) vacation spot. Sure, we’re going to construct just for iOS gadgets, not for Simulators. Now, you want solely faucet Command + B.

Any iOS machine (arm64) vacation spot

To get our baked framework we have to go to Derived information and take it from there. You must open the Derived information folder from Xcode: Go to Xcode Preferences (cmd + ,), then open Areas, and faucet on the arrow on the finish of the Derived information path.

Within the Derived information folder, discover your mission and use this path:
Construct / Merchandise / Debug-iphoneos / SwiftCodeKit.framework

Derived information with SwiftCodeKit mission

Unity mission

It’s time to arrange our Unity mission. Open Unity and create a mission; I referred to as it UnityClientProject.

Making a Unity mission

Within the Unity mission, you’ll find folder property. Drag your SwiftCodeKit.framework and drop it to the Belongings folder.

SwiftCodeKit.framework in Belongings / iOS folder

Relating to UI in Unity, we’re going to make a easy button. This button will summon our SwiftCodeKit View Controller. Proper-click on Hierarchy, select UI, after which Button.

Button in Unity mission

Additionally, within the hierarchy, now we have to make one other object for our button. I name it ButtonController. Within the inspector of the ButtonController, add a element / new script and identify it ButtonControllerScript.cs. Open this file.

Truly, we’d like just one public methodology: OnPressButton(). However earlier than that, now we have to import System.Runtime.InteropServices. This may assist us to acknowledge our strategies from the SwiftCodeKit.framework. If you happen to keep in mind, now we have just one public perform: startSwiftCodeKitController(), so let’s import it utilizing DllImport.

ButtonController.cs handles methodology from iOS utilizing Runtime.InteropServices

Constructing Unity mission

We’re able to construct our iOS mission from Unity. Open File / Construct Settings and alter the Platform to iOS. Then press Construct.

Unity construct settings

After urgent construct it should mechanically run an Xcode mission. This mission is generated by Unity and there you will note just one Framework referred to as UnityFramework.

A few issues you possibly can come across at this second: the primary one — it’s a must to signal this mission and the second is the bitcode error — this could solely occur when you use Xcode 14. It’s not so massive deal. Let’s simply disable bitcode on this mission, and run it once more.

Xcode Construct settings

In your iPhone, you will note your Unity app. The primary blue display screen with a button — that is the Unity half and the orange introduced display screen is your framework!

Let’s rapidly undergo what we did:

  1. Ready a Framework with a public methodology for iOS and for C# utilizing @_cdecl attribute.
  2. Created a easy Unity mission with a button on the middle.
  3. Added our Framework to the property of the Unity mission.
  4. Ready the ButtonController object with C# script the place we imported our methodology utilizing System.Runtime.InteropServices
  5. Constructed an iOS mission from Unity.

As you possibly can see these are fundamental steps that give you a chance to know the way it works. Partly two (see under) we are going to attempt to make this mission nearer to actual utilization. We’ll experiment with @_cdecl attribute and discover the constraints.

This text is written in two components. Within the second half, we are going to experiment with @_cdeclto know the constraints of interoperability of Swift and C#. Let’s get began.

If you happen to learn the primary a part of this text you need to keep in mind the SwiftCodeKitBridging.swift file:

On this file, we retailer an inventory of public strategies for exposing, utilizing @_cdecl attribute. As you possibly can see we already know easy methods to name some capabilities from C#. However clearly, it’s not so usable as a result of in actual iOS purposes we use capabilities with parameters, our capabilities return some values, furthermore, we use closures, delegates, and so forth. How do expose this code to the Unity mission?

Let’s resume what we’re gonna attempt at this time:

  • Operate with parameters
  • Operate returns worth
  • Operate with closure

iOS framework replace

I ready a small replace of our SwiftCodeKitViewController.

I added two extra views: UILabel and UIStepper. Utilizing stepper management we are able to increment and decrement a price and set it to the label.

SiwftCodeKit UI

It will likely be sufficient to experiment with actual UI. Let’s check out our public class:

As you possibly can see this class was prolonged with strategies that we’re going to use in C#. Essentially the most attention-grabbing half is the Delegates — they’re represented by closures. Let’s join all these strategies to our UI. In viewDidLoad, add our first delegate methodology SwiftCodeKit.swiftCodeKitDidStart?().

Right here’s different strategies that can be utilized in extensions:

iOS framework bridging strategies

All our public strategies needs to be acknowledged from C#. I recommend strolling by them one after the other.

Right here’s the perform with parameters:

Capabilities with parameters

Operate returns a price (Double):

Operate returns worth as double

The perform returns a string. Right here you possibly can discover a distinction. Particularly for this sort of information, we have to allocate reminiscence and move our string to strdup() — this methodology will duplicate the string for UnsafePointer().

Operate returns worth as String

OK, now Delegates. As you possibly can see they’re capabilities with escaping closures. However apart from escaping closure has some attention-grabbing add-on referred to as@conference(c)

There’s a quick description from docs.swift.org:

Apply this attribute to the kind of a perform to point its calling conventions. The c argument signifies a C perform reference. The perform worth carries no context and makes use of the C calling conference.

Delegates

OK, let’s construct our up to date framework, get this construct, and drop it into the Unity mission property folder (see half 1 for a way to do that).

Unity ButtonControllerScript replace

Our C# script file has just one imported perform for now: startSwiftCodeKitController, so it’s time so as to add the remainder of them. We’ll stroll by the identical manner as we did with Swift strategies:

Right here’s the perform with parameters:

Operate with parameters in ButtonCotrollerScript.cs

This perform returns a price, as proven under:

Operate returns a price in ButtonCotrollerScript.cs

And Delegates utilizing AOT:

Delegates in ButtonControllerScript.cs

The very last thing we’re going to do is to replace OnPressButton() methodology the place we use all strategies from our Swift framework.

OnPressButton() replace in ButtonControllerScript.cs

Straight from Unity we configured our iOS Controller and used our three delegates. Now, it’s time to construct our mission. If you happen to adopted me appropriately and all of your strategies have been recognizable by Unity, your consequence will seem like the next:

Unity iOS mission launched from Unity

The console of XCode ought to print one thing like this:

SwiftCodeKit did begin
SwiftCodeKit get worth: 10
SwiftCodeKit get model: Swift Code Equipment 0.0.1
SwiftCodeKit worth did change. Worth: 11
SwiftCodeKit worth did change. Worth: 12
SwiftCodeKit worth did change. Worth: 13
SwiftCodeKit did end

I at all times ask the identical query each time I finalize a job: How can I make this higher? I feel this job might be improved endlessly. I’m not an skilled with Unity (if you understand higher, please remark), however I do know that we are able to even construct DLL Library with all our capabilities and ultimately simply import this construct on to the script.

Additionally, as an iOS developer utilizing UnsafePointer remember that this reminiscence needs to be launched.

Thanks for studying.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments