[Unity3d] Unity3d game development Lua and the game's indissoluble bond (next)

Source: Internet
Author: User

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------

Like my blog Please remember my name: Qin Yuanpei , my blog address is Blog.csdn.net/qinyuanpei.

Reprint please indicate the source, this article Qin Yuanpei , this article source: http://blog.csdn.net/qinyuanpei/article/details/40050225

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------


      Friends, hello, I am Qin Yuanpei, welcome everyone to pay attention to my blog, my blog address is Blog.csdn.net/qinyuanpei. In the first two articles, Bo and everyone learned how to use LUA in game development, and today we continue to learn the application of the Lua language in game development, and today we convert our perspective to the familiar unity platform, so why should we introduce the LUA language into the unity platform? This is the first question that we have to think about today. Traditional stand-alone games are usually sold to game players in the form of a game disc, players can not get more game content after purchasing the game, players only in a limited capacity of the game CD-ROM constantly repeated to find the fun of the game. Undoubtedly, this model is not conducive to game developers to add new content to the game. However, with the gradual maturity of internet technology, after buying a physical game, players can usually buy DLC to experience the richer game content, while the game maker can convey the content of the game to the player through DLC. We know that DLC is a piece of information that usually refers to a game, and it is a complement to the content of the game. Technically speaking, if we use a compiled language to make a game, then we simply cannot achieve the expansion of the game content, because we need to recompile the entire project and then package it into a game disc and then sell it to the player. This will undoubtedly increase the production cost of the game maker, and more importantly, the player will not buy the game for the new game content, obviously this way is unreasonable. Then, a scripting language like Lua can play a huge role, because scripting languages don't usually take up too much resources, and maybe we just need a game script to create a new game plot with the existing scenes and characters in the game. Therefore, after some analysis, we can summarize the scripting language in the game development of an important role is to update. Because scripting languages are usually plain text files, we just need to change some parameters without recompiling the entire project, which is what we want to see.

Well, let's learn how to use the Lua language in the Unity3d project, Unity3d based on mono virtual machines, so theoretically. NET class libraries can be used directly in Unity3d. But given the Unity3d cross-platform needs, the tools we choose must be well supported on every platform. The luainterface mentioned in the previous article can theoretically be used in Unity3d, but since iOS does not support the reflection mechanism, we cannot use this class library directly in Unity3d. In the open source community, Bo Master found the Cloud wind team Ananda development of the Unilua, Cloud Wind team is a game development in the domestic area of the more famous people, then we today to choose Unilua as one of our tool library, the project is an open source project, The Luainterface project was referenced, but a new approach was used to deal with the problem of reflection, so it is now perfectly supported for each platform. I believe you have the foundation of the previous two articles, now you can calmly face the LUA API. Well, let's now create a simple unity project:

The first step is to download Unilua:http://github.com/xebecnan/unilua. There are two ways to refer a Unilua to a project, one is to compile the Unilua in the project into a DLL and then use it in a unity project, one to copy the Unilua in the project directly into the Unity project, and we use the second method here because the blogger is lazy and hehe. Add the Unilua namespace to our project and we can start writing programs. But here, the blogger would like to say that mono may have caused a mistake, it is estimated that Ananda in writing this project was used. NET4.0 versions above, and versions above. NET4.0 are constructors that support default parameters. However, since Mono uses. NET3.5 By default, it will error when compiling the project, we can pass the project->assembly-csharp->build-> General set the target framework for. NET to 4.0 so that it can be solved. Well, let's start with the code, and first create a InvokeScript.cs script:

Using unityengine;using system.collections;using Unilua;public class Invokescript:monobehaviour {//lua script file, we will be in C # Call the script public Textasset Luafile;//lua virtual machine private iluastate mlua;void Start () {//Initialize LUA virtual machine mlua=luaapi.newstate ();// Load LUA standard library mlua.l_openlibs ();//Refer to a static C # library Mlua.l_requiref (csharplib.classname,csharplib.initlib,false); Execute LUA script mlua.l_dostring (luafile.text);} void Ongui () {if (Guilayout.button ("Call Lua script", Guilayout.height ()) {Invokelua ()}; if (Guilayout.button ("Call C # Script", Guilayout.height ())) {Invokecsharp ();}} #region Call C # script void Invokecsharp () {//Get the method and pass in the parameter Mlua.getglobal ("Sumandsub"); Mlua.pushinteger (8); Mlua.pushinteger ); Mlua.pcall (2,4,0);} #endregion #region calls the Lua script void Invokelua () {//Gets the arg1 parameter Mlua.getglobal ("Arg1") in the Lua script;//Output Arg1Debug.Log (" The variables in the Lua script arg1= "+mlua.l_tostring (-1));//Get the ARG2 parameter Mlua.getglobal (" Arg2 ") in the Lua script;//Output Arg2Debug.Log (" variable arg2= in Lua script +mlua.l_tostring (-1));//Get the printf method Mlua.getglobal ("printf") in the Lua script;//Call the printf method Mlua.pcall (0,0,0) in the Lua script;// Gets the sum method Mlua.getglobal ("sum") in the Lua script;/Incoming Parameters 12 and 25mlua.pushinteger (25);//Call this method Mlua.pcall (2,3,0);//Get incoming two arguments and sum result int a= Mlua.tointeger ( -3); int B=mlua.tointeger ( -2); int Sum=mlua.tointeger (-1);//Output Debug.Log ("Call the Sum method in Lua script:" +a+ "+" +b+ " = "+sum);} #endregion}
In this script, we first initialized the LUA environment, which is the same as we use LUA in C + +, because Unilua maintains a high degree of consistency in naming and LUAAPI when designing the API, and if you are familiar with the LUA API, So now it's going to be easy for you. Next, we introduced a C # library that we wrote in the form of require, which is a static library that encapsulates the C # method for a LUA script invocation, as we'll talk about later. Next, we loaded a LUA script file through Unity's assettext, which has a file extension of. txt because we only need the content of the Lua script. In the script we defined two methods Invokelua and Invokesharp to invoke the Lua script and the C # script, respectively. Well, next, let's focus on Lua calling this part of the C # script because Unilua is not the same as luainterface in calling the function, so we can no longer use the original C # method and then like the Lua scripting method, but the blogger feels the same principle here, But Unilua provides a better way to bind the mechanism, let's look at the following script:

using Unityengine;using system.collections;using unilua;public Static Classes csharplib{//The current class file name, we will use this name in the Lua script public Const string Classname= "CSharpLib.cs";//c# library initialization public static int initlib (Iluastate lua) {namefuncpair[] Define=new Namefuncpair[]{new Namefuncpair ("Sumandsub", Sumandsub),};lua. L_newlib (define); return 1;} We define a method of summing difference in C # public static int sumandsub (Iluastate lua) {///first parameter int A=lua. L_checkinteger (1);//The second parameter int B=lua. L_checkinteger (2);//calculation and int c=a+b;//calculate the difference int d=a-b;//the parameters and calculation results into the stack lua. Pushinteger (a); Lua. Pushinteger (b); Lua. Pushinteger (c); Lua. Pushinteger (d);//There are four return values, although returning multiple values is not supported in C #, this is the supported return 4 in Lua;}} 

We must note that there is a Namefuncpair class here, which is the method used to bind a C # method to a Lua method in Unilua, we first construct such a namefuncpair array and then add it to the Lua_l_newlib () parameter, which is equivalent to registering a library, I think it should be registered a method collection. And classname is a constant that represents the name of the current class, and can take any character, where we use the file name of the class we'll look at in the Lua script using this value to find the current class. Next, we can see that the blogger constructs a C # method with a sum of difference, which is consistent with the method defined in the LUA API, that is, we need to specify the number of worthwhile methods that the method will return. If we need to return a value, we'll push it through the push-series method into the stack. Here we return four values, everyone will say Hello is C # also supports the return of multiple values Ah, actually, this is the LUA language provides us with a benefit ah, such as we need to return an object in the 3D world coordinates, usually we need to use three assignment statements to get it, but you use LUA, A line of code can be done. OK, now let's go back to the start method of the Invokescript script, you can notice that there is a l_requiref () method, the front is just an understatement to say it introduced a library, so now let's see what it specifically does, the first parameter represents the name of this class, Point to our defined classname, the second parameter is the initialization method of this class to the Initlib () method, the third parameter is whether to use this library in the global space, here we choose false. Okay, so we're done writing the C # script. OK, here we create a plain text file in the project, we enter the following code:

Local Csharplib=require "CSharpLib.cs" arg1= "Unity3d" arg2= "Unreal" arg3= "coco2dx" function Printf ()  print ("This Is the methods invoked in Lua ") Endfunction Sum (A, b)  return a,b,a+bendfunction sumandsub (A, b)  print (csharplib. Sumandsub (A, b)) end
The first line of code is also a require method, which is a method of referencing a library in a LUA script that can reference the standard library of Lua, as well as referencing the external libraries we define, and you notice that the names here are the same as the classname we defined earlier, Because we are querying this library by this name, we have registered this library in the LUA environment, so we can only refer to this library now. In this script we define a few character-type variables, two LUA methods, and a C # method wrapped in Lua. OK, now we assign this text file to Invokescript's Luafile field, we get the script content through Luafille's text, and then execute the contents of the script through the Dostring () method, notice that the C # Library is registered first. The contents of the script are then executed, or an error occurs. Well, finally, let's see how it works:


As you can see in the Lua script called by C # we get the two variables in the script arg1, arg2, call the two methods defined in Lua, and the last method, as we wish, returns four values, which is exactly what we want. Here, by the way, the Print method and return in Lua can be output directly in debug after call, without having to do the log again. Well, today's content is this, I hope you like Ah, welcome to my blog, in the next article, Bo will lead everyone to continue Lua, please pay attention to Bo Master's next article "Unity3d Game development of Lua and game of the indissoluble end: Unilua Hot Update full Interpretation", Thank you. For Unilua calling non-static classes and methods, you can refer to this article: http://www.cnblogs.com/cqgreen/p/3483026.html.



Daily Proverbs: The right place to live, not close to the money, nor close to the right, but close to the soul, true happiness, neither wealth nor everything is right, but a clear conscience.




--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------

Like my blog Please remember my name: Qin Yuanpei , my blog address is Blog.csdn.net/qinyuanpei.

Reprint please indicate the source, this article Qin Yuanpei , this article source: http://blog.csdn.net/qinyuanpei/article/details/40050225

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------


[Unity3d] Unity3d game development Lua and the game's indissoluble bond (next)

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.