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);
        }
    }
}
相关推荐
mxwin7 分钟前
Unity Shader URP:法线如何进行光照计算
unity·游戏引擎·shader
wb0430720118 分钟前
仓库搬家不停业——从阿明的“在线换仓库“,看数据库迁移与 Schema 演进的实战方法论
数据库·adb·架构
郝学胜-神的一滴40 分钟前
中级OpenGL教程 009:用环境光告别模型死黑
前端·c++·unity·godot·图形渲染·opengl·unreal
Mr -老鬼2 小时前
EasyClick 入门指南:Shell 命令与 ADB 完全指南
android·adb·自动化·shell·easyclick·易点云测
feifeigo1233 小时前
C# ADB 安卓设备数据传输工具
android·adb·c#
2301_773643623 小时前
mysql5.7稳定版使用
adb
mxwin12 小时前
Unity URP 中的法线生成完全指南
unity·游戏引擎
游乐码12 小时前
Unity基础(十五)LineRender画线功能
unity·游戏引擎
小贺儿开发14 小时前
Unity3D 图片循环查看器
unity·工具·图片·列表·循环·ugui·互动
ULIi096kr19 小时前
MySQL解决Too many connections报错:连接数爆满排查、优化与永久解决方案
数据库·mysql·adb