toLua[三] Examples 02_ScriptsFromFile分析

本文意在分析toLua的第二个Example:02_ScriptsFromFile

一.运行工程

点击DoFile和Require都会打印两行文本,区别是DoFile会每次打印,Require只会打印一次

二.API分析

首先

string fullPath = Application.dataPath这行需要修改,直接下载到的路径是错误的

下面是正确的路径,可以加上对fullPath的打印

cs 复制代码
string fullPath = Application.dataPath + "/LuaFramework/ToLua/Examples/02_ScriptsFromFile";
cs 复制代码
using UnityEngine;
using System.Collections;
using LuaInterface;
using System;
using System.IO;

//展示searchpath 使用,require 与 dofile 区别
public class ScriptsFromFile : MonoBehaviour 
{
    LuaState lua = null;
    private string strLog = "";    

	void Start () 
    {
#if UNITY_5 || UNITY_2017 || UNITY_2018		
        Application.logMessageReceived += Log;
#else
        Application.RegisterLogCallback(Log);
#endif         
        lua = new LuaState();                
        lua.Start();
        //如果移动了ToLua目录,自己手动修复吧,只是例子就不做配置了
        string fullPath = Application.dataPath + "/LuaFramework/ToLua/Examples/02_ScriptsFromFile";
        lua.AddSearchPath(fullPath);
    }

    void Log(string msg, string stackTrace, LogType type)
    {
        strLog += msg;
        strLog += "\r\n";
    }

    void OnGUI()
    {
        GUI.Label(new Rect(100, Screen.height / 2 - 100, 600, 400), strLog);

        if (GUI.Button(new Rect(50, 50, 120, 45), "DoFile"))
        {
            strLog = "";
            lua.DoFile("ScriptsFromFile.lua");                        
        }
        else if (GUI.Button(new Rect(50, 150, 120, 45), "Require"))
        {
            strLog = "";            
            lua.Require("ScriptsFromFile");            
        }

        lua.Collect();
        lua.CheckTop();
    }

    void OnApplicationQuit()
    {
        lua.Dispose();
        lua = null;
#if UNITY_5 || UNITY_2017 || UNITY_2018	
        Application.logMessageReceived -= Log;
#else
        Application.RegisterLogCallback(null);
#endif 
    }
}

2.1 LuaState:AddSearchPath()

增加Lua文件的搜索目录

cs 复制代码
        string fullPath = Application.dataPath + "/LuaFramework/ToLua/Examples/02_ScriptsFromFile";
        lua.AddSearchPath(fullPath);

2.2 LuaState:DoFile(string fileName)

每次调用都会执行fileName文件,文件名可以加后缀.lua也可以不加

2.3 LuaState:Require(string fileName)

仅执行一次fileName文件, 不会重复执行

相关推荐
天人合一peng5 小时前
Unity中button 和toggle监听事件函数有无参数
前端·unity·游戏引擎
_乐无6 小时前
Unity加载gly 点云 高斯泼溅渲染
unity
坚定信念,勇往无前6 小时前
unity发布BuildWebGL.wasm 加载过慢
unity·wasm
avi911110 小时前
Unity Data Excel读取方法+踩坑记;和WPS Excel的一些命令
unity·游戏引擎·excel·wps·data
天人合一peng12 小时前
Unity 中Canvas 或image打勾时不显示
unity
淡海水1 天前
【节点】[Houndstooth节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·houndstooth
微:xsooop2 天前
iOS上架被拒4.3(a) 10次到过审历程
flutter·unity·ios·uniapp
jtymyxmz3 天前
《Unity Shader》14.1 卡通风格的渲染
unity·游戏引擎
天人合一peng3 天前
unity获得和修改button的text(TMP)
java·前端·unity
dzj20213 天前
Unity中使用LLMUnity遇到的问题(三)——如何配置和使用知识库
unity·llmunity·知识库大模型