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

相关推荐
weixin_4242946712 天前
Unity 调用Steamworks API 的 SteamUserStats.RequestCurrentStats()报错
unity·游戏引擎·steamwork
HoFunGames12 天前
Unity小地图,Easy Minimap System MT-GPS插件
unity·游戏引擎
wy32586436412 天前
Unity 新输入系统InputSystem(基本操作)
unity·c#·游戏引擎
WarPigs12 天前
着色器multi_compile笔记
unity·着色器
ECHO飞跃 01212 天前
Unity2019 本地推理 通义千问0.5-1.5B微调导入
人工智能·深度学习·unity·llama
Unity游戏资源学习屋12 天前
【Unity UI资源包】GUI Pro - Casual Game 专为休闲手游打造的专业级UI资源包
ui·unity
冰凌糕12 天前
Unity3D Shader 顶点法线外扩实现描边效果
unity
小菱形_12 天前
【Unity】TimeLine
unity·游戏引擎
小贺儿开发13 天前
Unity3D 自动化物流分拣模拟
运维·科技·unity·自动化·人机交互·传送带·物流分拣
EQ-雪梨蛋花汤13 天前
【3D可视化】基于 Unity 的智慧体育馆三维信息可视化大屏实践
3d·unity·信息可视化