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);
        }
    }
}
相关推荐
lrh30252 小时前
Custom SRP 12 - HDR
3d·unity·srp·render pipeline
霜绛3 小时前
Unity:Json笔记——Json文件格式、JsonUtlity序列化和反序列化
学习·unity·json·游戏引擎
九皇叔叔11 小时前
Docker 镜像维护指南:从配置优化到 MySQL 实战运行
mysql·adb·docker
muxin-始终如一11 小时前
MySQL分区分表实现方法详解
数据库·mysql·adb
TYayyyyy14 小时前
unity 事件、委托
unity
2501_9293826514 小时前
电视盒子助手开心电视助手 v8.0 删除电视内置软件 电视远程控制ADB去除电视广告
android·windows·adb·开源软件·电视盒子
L X..14 小时前
Unity反射调用 ReactiveProperty<T>(泛型类型)内部方法时崩溃
unity·c#·游戏引擎·.net
向宇it20 小时前
【推荐100个unity插件】将您的场景渲染为美丽的冬季风景——Global Snow 2
unity·游戏引擎·风景
浅丿忆十一20 小时前
关于unity一个场景中存在多个相机时Game视图的画面问题
unity·游戏引擎
WLJT1231231231 天前
方寸之间见天地:新兴高端印章的当代破局与价值重构
unity·游戏引擎