Skills training for LUA Unity3d game development

Source: Internet
Author: User
Tags lua

Below we start today's unity3d skills training. We learn Unity3d training goals: let U3d beginners can more quickly grasp the u3d technology, make changes to their own materials, can be completed independently 2D, 3D small-scale games and web game development.

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. Well, let's now create a simple unity project:

The first step is to download 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:

[CSharp] View plaincopyprint?
  1. Using Unityengine;
  2. Using System.Collections;
  3. Using Unilua;
  4. Public class Invokescript:monobehaviour {
  5. //lua script file, we will call the script in C #
  6. Public Textasset Luafile;
  7. //lua virtual Machines
  8. private Iluastate Mlua;
  9. void Start ()
  10. {
  11. //Initialize LUA virtual machine
  12. Mlua=luaapi.newstate ();
  13. //Loading LUA standard library
  14. Mlua.l_openlibs ();
  15. //Refer to a static C # library
  16. Mlua.l_requiref (Csharplib.classname,csharplib.initlib,false);
  17. //Execute LUA script
  18. Mlua.l_dostring (Luafile.text);
  19. }
  20. void Ongui ()
  21. {
  22. if (Guilayout.button ("Call Lua script", Guilayout.height ( )))
  23. {
  24. Invokelua ();
  25. }
  26. if (Guilayout.button ("Call C # Script", Guilayout.height ( )))
  27. {
  28. Invokecsharp ();
  29. }
  30. }
  31. #region Calling C # script
  32. void Invokecsharp ()
  33. {
  34. //Get method and pass in parameter
  35. Mlua.getglobal ("sumandsub");
  36. Mlua.pushinteger (12);
  37. Mlua.pushinteger (8);
  38. Mlua.pcall (2,4,0);
  39. }
  40. #endregion
  41. #region calling the Lua script
  42. void Invokelua ()
  43. {
  44. //Get the ARG1 parameter in the Lua script
  45. Mlua.getglobal ("arg1");
  46. //Output arg1
  47. Debug.Log ("variable arg1= in Lua script" +mlua.l_tostring (-1));
  48. //Get the ARG2 parameter in the Lua script
  49. Mlua.getglobal ("arg2");
  50. //Output arg2
  51. Debug.Log ("variable arg2= in Lua script" +mlua.l_tostring (-1));
  52. //Get the printf method in the Lua script
  53. Mlua.getglobal ("Printf");
  54. //Call the printf method in the Lua script
  55. Mlua.pcall (0,0,0);
  56. //Get the sum method in the Lua script
  57. Mlua.getglobal ("Sum");
  58. //Incoming parameters 12 and
  59. Mlua.pushinteger (12);
  60. Mlua.pushinteger (25);
  61. //Call this method
  62. Mlua.pcall (2,3,0);
  63. //Get incoming two parameters and sum result
  64. int A=mlua.tointeger (-3);
  65. int B=mlua.tointeger (-2);
  66. int Sum=mlua.tointeger (-1);
  67. //Output
  68. Debug.Log ("Call the Sum method in the Lua script:" +a+"+" +b+"=" +sum ");
  69. }
  70. #endregion
  71. }
[CSharp] View plaincopyprint?

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 principle is the same, But Unilua provides a better way to bind the mechanism, let's look at the following script:

[CSharp] View plaincopyprint?
  1. Using Unityengine;
  2. Using System.Collections;
  3. Using Unilua;
  4. Public static class Csharplib
  5. {
  6. ///Current class file name, we will use this name in Lua script
  7. Public const string classname="CSharpLib.cs";
  8. //c# Library Initialization
  9. public static int initlib (iluastate lua)
  10. {
  11. Namefuncpair[] define=new namefuncpair[]
  12. {
  13. New Namefuncpair ("Sumandsub", sumandsub),
  14. };
  15. Lua. L_newlib (define);
  16. return 1;
  17. }
  18. //We define a method of summing difference in C #
  19. public static int sumandsub (iluastate lua)
  20. {
  21. //First parameter
  22. int A=lua.  L_checkinteger (1);
  23. //second parameter
  24. int B=lua.  L_checkinteger (2);
  25. //Calculation and
  26. int c=a+b;
  27. //Calculation poor
  28. int d=a-b;
  29. //Press the parameters and calculation results into the stack
  30. Lua. Pushinteger (a);
  31. Lua. Pushinteger (b);
  32. Lua. Pushinteger (c);
  33. Lua. Pushinteger (d);
  34. //has four return values, although returning multiple values is not supported in C #, this is supported in Lua
  35. return 4;
  36. }
  37. }

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 parameters of the Lua_l_newlib () , which is equivalent to registering a library, I think it's about registering a collection of methods. And classname is a constant that represents the current class name 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 that sums the difference, This method is consistent with the method defined in the LUA API, which means that we need to specify the number of values that the method will return. If we need to return a value, we'll push it through the push-series method. Here we return four values, everyone will say Hello is C # also supports the return of multiple values Ah, actually, This is a benefit that the LUA language provides to us, like we need to return an object's coordinates in the 3D world, and normally we need to use three assignment statements to get it, but if you use Lua, A line of code can be done. OK, now we go back to the start method of the Invokescript script, you can notice that there is a l_requiref () method, the front just lightly said that it introduced a library, so now we see what it specifically did it, The first parameter represents the name of the class, points to our defined classname, the second parameter is the initialization method of the class to the Initlib () method, and the third parameter is whether to use the library in global space, where we choose false. Okay, so we're done with C # Scripting. OK, here we create a plain text file in the project, we enter the following code:

[Plain] View plaincopyprint?
    1. local csharplib=require "CSharpLib.cs"   
    2. arg1= "Unity3d"   
    3. arg2= "Unreal"   
    4. arg3= "Coco2dx"   
    6. function printf ()   
    7.   print ("this is the  methods invoked in lua ")   
    8. end  
    10. Function sum (A, b)   
    11.   return a,b,a+b   
    12. end  
    14. Function sumandsub (A, b)    
    15.   print (csharplib. Sumandsub (A, b))   
    16. 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 have defined several character variables, two LUA methods, one LUA-packaged C # method. 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, That's what we want. By the way, the Print method and return in Lua can be output directly in debug after call, without having to do the log. More wonderful Unity3d technical articles please click Http://

Skills training for LUA Unity3d game development

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: 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.