Unity3d game Development of C + + plug-in access

Source: Internet
Author: User
Tags rand

Hello everyone friends, I am Qin Yuanpei , Welcome to pay attention to my blog, my blog address is http://qinyuanpei.com. Although the Unity3d engine relies on powerful cross-platform capabilities Belittlin ' the world of game engines, we basically don't touch the underlying things when we use the Unity3d game engine, but sometimes we have to consider using C + + when we are faced with some wonderful requirements. Such a language to write the relevant plug-ins for them. If you ask me what kind of wonderful requirements, such as access to Bluetooth handles to control the game, access to similar arcade devices to control the game, access the same game to two different devices and respond to different control ... These kinds of problems, may not find a solution in the Unity3d engine, this time write C + + plug-in becomes a kind of rigid demand, this is the problem we are going to discuss together today.

Unity3d mainly uses C # for development, so writing plug-ins for Unity3d is essentially making C # invoke C + + code. There are currently two implementations of C + + CLR and C + + native, where the C + + CLR can be understood as C + + code that runs on the. Net CLR, the common language runtime, which is managed C + + code and is not recognized by C + + standards because it is more like C + + Mixed code in both languages, the advantage of this code can be as common as the. NET library is called by C #, considering that Unity3d is built on a mono similar to. NET, so this approach should be our best practice; C + + native refers to the traditional C + + dynamic link library, which is called in C # after being packaged in C # by DllImport , rather than unmanaged C + + code invoked in this way, it is believed that friends who have contacted Windows development should not feel unfamiliar, it is a more common method, for example, when we want to connect to the Apple SDK, we need to encapsulate the code of object C and give it to C # to invoke it. And the method used here is dllimport.

OK, let's take a look at how each of the two approaches is implemented. The development environment that bloggers use here is the version 4.6 version of Windows 8.1 32bit and Visual Studio 2012,unity3d. C + + CLR Create a C + + CLR class Library project

First, we create a C + + CLR project by following the steps in the figure below:

Please note that. NET version of the problem, the important thing to say three times, do not seriously look at the people here do not come to me to comment on, I hate even the article did not see to understand and you are entangled with the people, thank you. When you create a project, open the Project Properties window to set the value of the common language Runtime support node to secure MSIL Common language Runtime Support (/clr:safe) OK, let's find the CLR4Unity.h file and add the ExampleClass declaration:

<summary>///A simple managed C + + example class///</summary> public ref class ExampleClass {public:///<summ Ary>///produces an integer random number between min and max///<returns> integer random number </returns>///<param name= "min" > Minimum < /param>///<param name= "Max" > Max </param>///</summary> static int Random (int min,int m AX) {//note using gcnew in Managed C + + instead of new//I admit C + + write CLR code slightly exotic like a mixed return (gcnew system::random) of C + + and C # syntax-
    >next (Min,max); ///<summary>///calculates the squared///<returns> integer value of an integer </returns>///<param name= "A" > needs to be flat
    Square value </param>///</summary> static int Square (int a) {return a * A; ///<summary>///Returns the maximum value of two digits///<returns> integer value </returns>///<param name= "a" > Parameter
    1</param>///<param name= "B" > Parameter 2</param>///</summary> static int Max (int a,int b) {if (a&LT;=B) {return B;
        }else{return A; }
    }
};

Obviously we've defined three simple methods here, and notice that the first method random depends on the System.rnadom class, while in Managed C + + the gcnew is used instead of the new keyword, so feel free to enjoy the mix of C # and C + + syntax style. This allows us to compile the class library of CLR4Unity.dll, copy the file to the plugins directory in the Unity3d project, and then add it to the project reference list. If you think the reference is:

Using Clr4unity;

Oh, I seriously doubt that you are right. NET familiarity degree. You have not added a reference to CLR4Unity.dll, what exactly are you using?

If you're right. NET familiar enough to ignore everything here, please close your eyes and then look down, haha. adding references and method calls in C #

Next we create a script PluginTest.cs in Unity3d, and then add the following code in the Ongui method. But you have to think that the code should be written in the Ongui method, I'm sorry you have to understand the Monobehaviour class first. What the. Added the code to the error. If you have no using, please do it by yourself:

Invoke method in C + + CLR
(Guilayout.button ("Invoke methods in C + + CLR, guilayout.height ()) 
{Debug.Log" ("Invoke C +
    + Methods in the CLR Random (0,10): "+ exampleclass.random (0,10));
    " Debug.Log ("Invoke Method Max (5,10) in the C + + clr:" + Exampleclass.max (5,10));
    Debug.Log ("Invoke Method Square (5) in the C + + clr:" + exampleclass.square (5));
}
C + + Native Create a C + + dynamic link library project

First we follow the steps in the following figure to create a C + + Win32 project:

Okay, next we find Native4Unity.cpp write the following code:

//Native4Unity.cpp: Defines the exported function of a DLL application. #include "stdafx.h"//In order to use the rand () function to introduce the C + + standard library #include "stdlib.h"///<summary>///produces an integer random number between min and Max///< returns> integer random number </returns>///<param name= "min" > Minimum </param>///<param name= "Max" > Max </ param>///</summary> extern "C" __declspec (dllexport) int Random (int min,int max) {return rand ()% (max-m
In + 1) + min; ///<summary>///Returns the maximum value of two digits///<returns> integer value </returns>///<param name= "a" > Parameter 1</param >///<param name= "B" > Parameters 2</param>///</summary> extern "C" __declspec (dllexport) int Max (int a, int
    b) {if (a<=b) {return B;
    }else{return A; }///<summary>///calculates the square///<returns> integer value of an integer </returns>///<param name= "A" > needs the value of the square </para m>///</summary> extern "C" __declspec (dllexport) int Square (int a) {return a * A;} 

Similar to the C + + CLR, we use the standard C + + language to achieve the same functionality. Note that the rand () function is the content of the C + + standard library, so we added a reference to the Stdlib.h header file at the beginning of the file. The point to note here is that all C + + methods that want to use DllImport to introduce C # should add the __declspec (dllexport) keyword to the method declaration unless it displays the methods in the. def file . The definition of a. def file can be retrieved on MSDN, which is part of the C + + compiler, and is not detailed here. using the DllImport encapsulation method in C #

After copying the compiled Native4Unity.dll into the plugins directory, the next thing we do is encapsulate or declare these methods in C #:

[DllImport ("native4unity")]
 private extern static int Random (int min, int max);

 [DllImport ("native4unity")]
 private extern static int Max (int a, int b);

 [DllImport ("native4unity")]
 private extern static int Square (int a);

And then it's simply called:

Invoke method in C + + native (
Guilayout.button ("Invoke method in C + + native, guilayout.height ())" 
{
    Debug.Log ("Invoke C + + Native in the method Random (0,10): "+ Random (0));
    " Debug.Log ("Method Max (5,10) to invoke C + + native:" + max (5,));
    Debug.Log ("Invoke Method Square (5) in C + + native:" + square (5));

The final program works as shown:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.