UnityEditor脚本:调用ADB推送文件到手机

因为经常要直接把工程文件推入到手机上跑真机测试,就做了一个,在工程内选中文件,推送到手机的简单脚本。

这里的根据项目需要,按文件的目录结够push进手机,如果只是推buddle,会更简单点,不做拓展了。

核心部分,unity调用ADB命令, 文件目录。

cs 复制代码
using UnityEngine;
using UnityEditor;
using System.Diagnostics;
using System.IO;

public class PushFileToPhone : EditorWindow
{
    [MenuItem("Tools/ADB/Push Selected File To Phone")]
    public static void OpenWindow()
    {
        GetWindow<PushFileToPhone>("Push File To Phone");
    }

    private string luaFolderPath = "Assets/Lua"; // Lua文件夹路径
    private string phonePath = "/storage/emulated/0/Android/data/com.xxx.dev/files/"; // 修改为目标可写目录

    void OnGUI()
    {
        GUILayout.Label("Push Selected File To Phone", EditorStyles.boldLabel);

        luaFolderPath = EditorGUILayout.TextField("Lua Folder Path", luaFolderPath);
        phonePath = EditorGUILayout.TextField("Phone Path", phonePath);

        if (GUILayout.Button("Push File"))
        {
            PushSelectedFile();
        }

        if (GUILayout.Button("Open Phone Path"))
        {
            OpenPhonePath();
        }
    }

    private void PushSelectedFile()
    {
        try
        {
            // 获取选中的文件路径
            string selectedFilePath = AssetDatabase.GetAssetPath(Selection.activeObject);
            if (string.IsNullOrEmpty(selectedFilePath))
            {
                UnityEngine.Debug.LogError("No file selected.");
                return;
            }

            UnityEngine.Debug.Log("Selected File Path: " + selectedFilePath);

            // 判断选中文件是否为txt文件
            if (!selectedFilePath.EndsWith(".txt"))
            {
                UnityEngine.Debug.LogError("Selected file is not a txt file.");
                return;
            }

            // 获取相对Lua文件夹的路径
            string relativePath = GetRelativePath(selectedFilePath, luaFolderPath);
            if (string.IsNullOrEmpty(relativePath))
            {
                UnityEngine.Debug.LogError("Selected file is not in the Lua folder.");
                return;
            }

            // 构建目标路径
            string targetPath = Path.Combine(phonePath, relativePath);
            UnityEngine.Debug.Log("Target Path: " + targetPath);
            // 创建目标目录
            string targetDir = Path.GetDirectoryName(targetPath);
            UnityEngine.Debug.Log("Target Directory: " + targetDir);
            CreateDirectory(targetDir);

            // 构建ADB命令
            string adbPath = GetAdbPath();
            string command = $"push \"{selectedFilePath}\" \"{targetPath}\"";

            // 执行ADB命令
            ProcessStartInfo processStartInfo = new ProcessStartInfo
            {
                FileName = adbPath,
                Arguments = command,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true
            };

            Process process = new Process { StartInfo = processStartInfo };
            process.Start();

            // 输出命令执行结果
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();
            process.WaitForExit();

            if (string.IsNullOrEmpty(error))
            {
                UnityEngine.Debug.Log("File pushed successfully: " + output);
            }
            else
            {
                UnityEngine.Debug.LogError("Error pushing file: " + error);
            }
        }
        catch (System.Exception ex)
        {
            UnityEngine.Debug.LogError("Exception: " + ex.Message);
        }
    }

    private string GetRelativePath(string filePath, string baseFolderPath)
    {
        // 确保基础文件夹路径以斜杠结尾
        if (!baseFolderPath.EndsWith("/"))
        {
            baseFolderPath += "/";
        }

        // 判断文件是否在基础文件夹内
        if (!filePath.StartsWith(baseFolderPath))
        {
            return null;
        }

        // 获取相对路径
        string relativePath = filePath.Substring(baseFolderPath.Length);
        relativePath = relativePath.Replace("\\", "/");
        return relativePath;
    }

    private void CreateDirectory(string dirPath)
    {
        try
        {
            // 构建ADB命令
            string adbPath = GetAdbPath();
            string command = $"shell mkdir -p \"{dirPath}\"";

            // 执行ADB命令
            ProcessStartInfo processStartInfo = new ProcessStartInfo
            {
                FileName = adbPath,
                Arguments = command,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true
            };

            Process process = new Process { StartInfo = processStartInfo };
            process.Start();

            // 输出命令执行结果
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();
            process.WaitForExit();

            if (!string.IsNullOrEmpty(error))
            {
                UnityEngine.Debug.LogError("Error creating directory: " + error);
            }
            else
            {
                UnityEngine.Debug.Log("Directory created successfully: " + dirPath);
            }
        }
        catch (System.Exception ex)
        {
            UnityEngine.Debug.LogError("Exception creating directory: " + ex.Message);
        }
    }

    private string GetAdbPath()
    {
        // 这里假设ADB工具已安装在系统环境变量中,直接返回"adb"即可
        // 如果ADB工具未安装在环境变量中,需要指定ADB工具的完整路径
        return "adb";
    }

    private void OpenPhonePath()
    {
        try
        {
            // 构建ADB命令
            string adbPath = GetAdbPath();
            string command = $"shell am start -a android.intent.action.VIEW -d \"file://{phonePath}\"";

            // 执行ADB命令
            ProcessStartInfo processStartInfo = new ProcessStartInfo
            {
                FileName = adbPath,
                Arguments = command,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true
            };

            Process process = new Process { StartInfo = processStartInfo };
            process.Start();

            // 输出命令执行结果
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();
            process.WaitForExit();

            if (string.IsNullOrEmpty(error))
            {
                UnityEngine.Debug.Log("Phone path opened successfully: " + output);
            }
            else
            {
                UnityEngine.Debug.LogError("Error opening phone path: " + error);
            }
        }
        catch (System.Exception ex)
        {
            UnityEngine.Debug.LogError("Exception opening phone path: " + ex.Message);
        }
    }
}
相关推荐
zdr尽职尽责21 小时前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
小Ti客栈3 天前
MySQL 常用函数速查(完整篇)
数据库·mysql·adb
ellis19703 天前
Claude Code[二] 上下文相关的机制
unity·ai编程
zdr尽职尽责4 天前
Unity 3C 动画系统:从「蜘蛛网」到可维护的动画架构
unity·架构·游戏引擎
国家一级摸鱼选手4 天前
[Unity]几何碰撞检测:SAT 分离轴定理详解(从数学原理到 C# 实现)
unity·c#·游戏引擎·分离轴定理(sat)·多边形相交
2035去旅行6 天前
ADB的底层原理
linux·adb·嵌入式·arm·soc
暴走约伯6 天前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质
寂寞的船7 天前
【Unity知识速递】第13期 Unity 内存泄漏排查实战:从 Memory Profiler 到 Lua 引用泄漏的生产级全链路诊断
unity·junit·c#·游戏引擎·lua
寂寞的船8 天前
【Unity Bug挑战】第12期 Awaitable 二次 await 死锁之谜 —— 为什么同一个异步操作等两次就卡死?
unity·c#·游戏引擎·bug
小呆爱发呆8 天前
第三章 MySQL 库表操作
数据库·mysql·adb