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文件, 不会重复执行

相关推荐
Hody9121 小时前
【XR开发系列】2025 年 XR 开发入门,我该选择 Unity 还是 Unreal Engine?
unity·xr·虚幻
DvLee10241 天前
UnityGLTF 材质创建与赋值流程
unity·材质
HahaGiver6661 天前
从0到1做一个“字母拼词”Unity小游戏(含源码/GIF)- 字母拼词正确错误判断
unity·游戏引擎·游戏程序
一个小狼娃2 天前
Android集成Unity避坑指南
android·游戏·unity
极客柒2 天前
Unity 协程GC优化记录
java·unity·游戏引擎
黄思搏2 天前
Unity SpriteRenderer 进度条 Shader 实现
unity·游戏引擎
猫屋小鱼丸2 天前
手把手教你在unity中实现一个视觉小说系统(一)
unity
HahaGiver6663 天前
Unity与Android原生交互开发入门篇 - 打开Unity游戏的设置
android·unity·交互
@LYZY3 天前
Unity TextMeshPro 文本对齐方式详解
unity·游戏引擎·textmeshpro·tmp
在路上看风景3 天前
2.1 ShaderLab - 渲染状态
unity