[Unity3D] Lua of Unity3D game development and unity3dlua

Source: Internet
Author: User

[Unity3D] Lua of Unity3D game development and unity3dlua

Certificate -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

If you like my blog, please remember my name: Qin Yuanpei. My blog address is blog.csdn.net/qinyuanpei.

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

Certificate -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


Dear friends, I'm Qin Yuanpei. Welcome to follow my blog. My blog address is blog.csdn.net/qinyuanpei. In the first two articles, the blogger and everyone learned about the application of Lua in the game development field. Today we continue to learn about the application of Lua in game development, today, we are switching our perspective to the familiar Unity platform. Why should we introduce Lua into the Unity platform? This is the first question we need to think about today. Traditional single-host games are usually sold to game players as game discs. After purchasing the game, players cannot obtain more game content, players can only repeatedly seek the fun of the game on a limited-capacity game disc. Undoubtedly, this mode is not conducive to game developers adding new content to the game. However, today, with the gradual maturity of internet technology, after buying a real game, players can usually purchase DLC to experience richer game content, the game producer can use the DLC to convey to the player the content that is not expressed in the game. We know that DLC is usually a game expansion piece, which is a supplement to the game content. Technically, if we use a compiled language to make a game, we cannot expand the game content at all, because we need to recompile the entire project, package it into a game CD, and then sell it to players. This will undoubtedly increase the production cost of the game producer, and more importantly, the player will not purchase the game again for the new game content. Obviously, this method is unreasonable. Then, a script language like Lua can play a huge role, because the script language usually does not occupy too much resources, perhaps we only need a game script to use the existing scenes and characters in the game to create new game plots. Therefore, after some analysis, we can conclude that an important role of scripting in game development is updating. Because the scripting language is usually a plain text file, we only need to change some parameters without re-compiling the entire project. This is exactly what we want to see.

Now let's take a look at how to use the Lua language in the Unity3D project. Unity3D is based on the Mono virtual machine, so theoretically. NET class libraries can be used directly in Unity3D. However, considering the need for Unity3D cross-platform, the tools we choose must be well supported on various platforms. The previously mentioned LuaInterface can be used in Unity3D theoretically. However, because IOS does not support the reflection mechanism, we cannot directly use this class library in Unity3D. In the open-source community, the blogger discovered the UniLua developed by Alan of the Yunfeng team. The Yunfeng team is a famous character in the domestic game development field, so today we will choose UniLua as a tool library. This project is an open-source project and has been referenced by the LuaInterface project, however, a new method is used to handle the reflection issue. Therefore, it is now perfectly supported by various platforms. I believe that with the foundation of the previous two articles, you can now easily access Lua APIs. Now, let's create a simple Unity project:

The first step is to download UniLua: http://github.com/xebecnan/unilua. There are two methods to reference UniLua to the project. One is to compile the UniLua in the project into a dll and then use it in the Unity project, one is to copy the UniLua in this project to the Unity project directly. Here we use the second method, because the bloggers are relatively lazy. Add the namespace of UniLua to our project, and we can start to write programs. Here, the blogger wants to say that Mono may cause an error. It is estimated that Arn was used when writing this project. for Versions later than NET4.0. versions later than NET4.0 support constructors with default parameters. However, Mono uses. NET3.5, so an error will be reported during Project compilation. We can use Project-> Assembly-CSharp-> Build-> General. NET's target framework is set to 4.0, which can solve this problem. Now let's start writing code. First, create a script for InvokeScript. cs:

Using UnityEngine; using System. collections; using UniLua; public class InvokeScript: MonoBehaviour {// Lua script file. We will call this script in C # public TextAsset LuaFile; // Lua Virtual Machine private ILuaState mLua; void Start () {// initialize the Lua Virtual Machine mLua = LuaAPI. newState (); // load the Lua standard library mLua. rochelle openlibs (); // reference a static C # library mLua. rochelle requiref (CSharpLib. CLASSNAME, CSharpLib. initLib, false); // execute the Lua script mLua. rochelle dostring (LuaFile. text);} void OnGUI () {if (GUILayout. button ("Call Lua script", GUILayout. height (30) {InvokeLua ();} if (GUILayout. button ("call C # script", GUILayout. height (30) {InvokeCSharp () ;}# region calls C # script void InvokeCSharp () {// gets the method and passes in the mLua parameter. getGlobal ("SumAndSub"); mLua. pushInteger (12); mLua. pushInteger (8); mLua. PCall (2, 4, 0) ;}# endregion # region calls Lua script void InvokeLua () {// obtain the arg1 parameter mLua in Lua script. getGlobal ("arg1"); // output arg1Debug. log ("arg1 =" + mLua. rochelle tostring (-1); // obtain the arg2 parameter mLua. getGlobal ("arg2"); // output arg2Debug. log ("arg2 =" + mLua. rochelle tostring (-1); // obtain the Printf method mLua In The Lua script. getGlobal ("Printf"); // call the Printf method mLua In The Lua script. PCall (0, 0, 0); // obtain the Sum method mLua In The Lua script. getGlobal ("Sum"); // input parameters 12 and 25mLua. pushInteger (12); mLua. pushInteger (25); // call this method mLua. PCall (, 0); // obtain two input parameters and the 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 the Lua Script:" + a + "+" + B + "=" + sum) ;}# endregion}
 

In this script, we first initialize the Lua environment, which is the same as using Lua in C ++, this is because UniLua maintains a high degree of consistency with LuaAPI during API design. If you are familiar with Lua API, it should be easy for you now. Next, we introduce a C # library written in the form of Require, which is a static library to encapsulate the C # method so that the Lua script can call it, this part will be discussed later. Next, we use the unityassettextfile to upload a Lua script file. The extension name of the script file is .txt, because we only need the content of the Lua script. In the script, we define two methods: InvokeLua and InvokeSharp to call the Lua script and C # script respectively. Well, next, we will focus on the part where Lua calls the C # script, because UniLua is calling a function, which is not the same as LuaInterface, therefore, we cannot register the C # method first and then use the Lua script method. However, the blogger thinks the principle here is the same, but UniLua provides a better method binding mechanism, let's look at the following script:

Using UnityEngine; using System. collections; using UniLua; public static class CSharpLib {// name of the current class file. 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. rochelle newlib (define); return 1;} // we define a method of summation difference in C # public static int SumAndSub (ILuaState lua) {// The first parameter int a = lua. rochelle checkinteger (1); // The second parameter int B = lua. rochelle checkinteger (2); // calculation and int c = a + B; // calculation difference int d = a-B; // press 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 multiple values cannot be returned in C #, return 4 is supported in Lua ;}}

You must note that there is a NameFuncPair class. This is the method used in UniLua to bind a C # Method to the Lua method. First, we construct such a NameFuncPair array, then add it to the lua_L_NewLib () parameter, which is equivalent to registering a library. I think it should be registering a method set. CLASSNAME is a constant that represents the name of the current class and can take any character. Here we use the file name of this class. We will use this value in the Lua script to find the current class. next, we can see that the blogger constructed a C # method with the sum difference. This method is consistent with the method defined in Lua API, that is, we need to specify the number of values returned by this method. if we need to return a value, we need to push it into the stack through the push series method. here we have returned four values. We will say hello that C # also supports returning multiple values. Actually, this is a benefit provided by Lua, for example, we need to return the coordinates of an object in the 3D world. Generally, we need to use three values to obtain the coordinates, but if you use Lua, A line of code is enough. okay, now let's go back to the Start method of the InvokeScript script. You can note that there is a Rochelle requiref () method. We just mentioned that it introduced a library, now let's take a look at what it has done. The first parameter indicates the name of this class and points to the defined CLASSNAME. The second parameter is that the initialization method of this class points to InitLib () method. The third parameter is whether to use this library in the global space. Here we select false. now, we have completed Writing C # scripts. now let's create a plain text file in the project, and 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. This is the method for referencing a library in the Lua script. This method can reference the standard library of Lua and also reference the external library we define, we have noticed that the name here is the same as the previously defined CLASSNAME, because we use this name to query this database, and we have registered this database in the Lua environment, so we can reference this library now. in this script, we define several variable types, two Lua methods, and one C # method packaged with Lua. now, we specify this text file to the LuaFile field of InvokeScript. We get the script content through LuaFille's text, and then execute the content in the script using the DoString () method, note that you must first register the C # library and then execute the content in the script. Otherwise, an error will occur. okay. Finally, let's take a look at the running effect:


We can see that in the Lua script called by C #, we get the two variables arg1 and arg2 in the script and call the two methods defined in Lua. The last method is as expected, it returns four values, which is the expected result. here, by the way, the print method and return method in Lua can output the results directly in Debug after the Call, without the need for Log. Well, today's content is like this. I hope you will like it. Welcome to pay attention to my blog. In the next article, I will lead you to continue Lua, please pay attention to the next article "Lua of Unity3D game development and endless gameplay final article: full interpretation of UniLua hot updates" by bloggers. Thank you. for details about UniLua calling non-static classes and methods, refer to this article: http://www.cnblogs.com/cqgreen/p/3483026.html.



Daily proverbs: a proper place in life, not close to money or power, but close to the soul. True happiness is neither rich nor right, but clear conscience.




Certificate -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

If you like my blog, please remember my name: Qin Yuanpei. My blog address is blog.csdn.net/qinyuanpei.

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

Certificate -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------



Unity3D game development instances, source code recommendation books, or download Source Code addresses

Unity 3D Game Development

[Unity3D] mobile 3D Game Development: how to use gravity sensing in Unity3D

Wang wanghai's laboratory, Shanghai laboratory-various graphics experiments, data structure experiments, and other trivial little notes are all gathered here for 0-various graphics experiments and data structures the lab and all other trivial notes are gathered here for 0 error (s ), 0 warning (s) the arrival of this magic moment error (s), 0 warning (s) the arrival of this magic moment learning Unity script is recommended: unity3D indexing gravity sensing is very common in mobile game development. Unity3D is a collection of gravity sensing related content. A simple JS script demonstrates the use of gravity sensing. CSDNGravity. js: // object texture var round: Texture2D; // The x y coordinate var x = 0 displayed on the screen; var y = 0; // maximum x y range displayed on the Object Screen var cross_x = 0; var cross_y = 0; function Start () {// initialization value cross_x = Screen. width-round. width; cross_y = Screen. height-round. height;} function OnGUI () {// The overall x y z gravity sensing gravity component GUI is displayed. label (Rect (0,0, 480,100), "position is" + Input. acceleration); // draw the object GUI. drawTexture (Rect (x, y, 256,256), round);} function Update ( ) {// Modify the object position based on the gravity component. Multiply the value by 30 here to make the object move faster x ++ = Input. acceleration. x * 30; y + =-Input. acceleration. y * 30; // avoid an object exceeding the screen if (x <0) {x = 0;} else if (x> cross_x) {x = cross_x ;} if (y <0) {y = 0;} else if (y> cross_y) {y = cross_y ;}} the Input here refers to the Input in Unity, acceleration is its gravity, and x and y represent its gravity. After creating the image, you only need to add the texture image: 12

Related Article

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.