使用Unity向其他程序传递参数,两个程序之间如何进行通信

使用Unity向其他程序传递参数

暂时没有什么事情做来玩啦。

unity的代码

只需要将脚本挂载到一个GameObject上即可。

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using Debug = UnityEngine.Debug;

public class PathObj : MonoBehaviour
{
    private string exePath = @"  c"//  "; //需要启动的程序路径启动程序的路径
    PathInformation pathInformation = new PathInformation();

    private void Awake()
    {
        Debug.Log("开始喽");
    }

    private void OnEnable()
    {
        //路径path的list,为对象赋值
        string pathA = @"C:\Users\123\Desktop\SourcePath\Aa.mp3";
        string pathB = @"C:\Users\123\Desktop\SourcePath\Bb.mp3";
        string pathC = @"C:\Users\123\Desktop\SourcePath\Cc.mp3";
        
        //将路径添加到路径的list,为对象赋值
        pathInformation.FilePathList.Add(pathA);
        pathInformation.FilePathList.Add(pathB);
        pathInformation.FilePathList.Add(pathC);
        
        //为对象赋值
        pathInformation.TargerPath = @"C:\Users\92126\Desktop\FilePath\test.mp3";

        
        //pathInformation转换成json,然后在另外一个程序将json解析出来
        string json = Newtonsoft.Json.JsonConvert.SerializeObject(pathInformation);
        Process pro = Process.Start(@exePath, json);//打开程序B,并传递参数。
		
        Debug.Log("结束");
    }
}

使用到的Process.Start()的文档,》文档链接
挂载上面这个东西。
下面是需要传递的参数对象。

using System;
using System.Collections.Generic;

    //需要传给另外一个程序的的参数的对象,会将这个对象给另外一个程序
    public class PathInformation//路径信息
    {
        private List<string> filePathList = new List<string>();//需要读取的文件路径列表

        private string targerPath;//目标路径

        public string TargerPath { get => targerPath; set => targerPath = value; }
        public List<string> FilePathList { get => filePathList; set => filePathList = value; }
    }

另外一个exe的代码

在另外一边,使用当exe启动的时候会获取到信息。

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;


namespace AudioSynthesis
{
    class Program
    {
		static  string TempPath;//需要从外面传过来
     	static  List<string> pathList = new List<string>();//路径路径信息

      public  static void Main(string[] args)//这里的string[] args是传过来的参数
        {
            Console.WriteLine("Hello World!");
			PathInformation pathInformation = JsonSerializer.Deserialize<PathInformation>(args[0]);//将传过来的参数进行转换。
			 
            pathList = pathInformation.FilePathList;
            TempPath = @pathInformation.TargerPath;


            List<byte[]> bytesList = new List<byte[]>();//读取到的文件的字节list

            FileStream fileStream = new FileStream(TempPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);//创建文件读取和写入流

			//根据路径,获取到信息,并将信息加入到bytesList,准备转化为bytes 
            for (int i = 0; i < pathList.Count; i++)
            {
                bytesList.Add(FileContent(pathList[i]));
            }

            var bytes = MergeBytes(bytesList);//将list<string>转换成bytes

            fileStream.Write(bytes, 0, bytes.Length);//向文件中写入字节数组
            fileStream.Flush();//刷新缓冲区
            fileStream.Close();//关闭流


            Console.WriteLine("文件写入读取完成");
		}
		
  /// <summary>
        /// 文件读取
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static byte[] FileContent(string filePath)
        {
            if (!File.Exists(filePath))
            {
                Console.WriteLine("文件不存在");
                return null;
            }

            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    byte[] buffur = new byte[fs.Length];
                    fs.Read(buffur, 0, (int)fs.Length);
                    fs.Flush();//刷新缓冲区
                    fs.Close();
                    return buffur;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }


        /// <summary>
        /// 将多个byte[] 合并成一个
        /// </summary>
        /// <param name="bytesList">byte[]  列表</param>
        /// <returns>合并之后的 byts [] </returns>
        private static byte[] MergeBytes(List<byte[]> bytesList)
        {

            int bytesLength = 0;//lbytesList中每一行byte元素的总长度

            for (int i = 0; i < bytesList.Count; i++)
            {
                bytesLength = bytesLength + bytesList[i].Length;
            }
            int k = 0;
            byte[] mergeBytes = new byte[bytesLength];//用于存储合并之后的 byts[] 

            for (int i = 0; i < bytesList.Count; i++)
            {
                for (int j = 0; j < bytesList[i].Length; j++)
                {
                    mergeBytes[k] = (bytesList[i])[j];
                    k = k + 1;
                }
            }
            return mergeBytes;
        }

	}
}


两个程序之间的通信

程序A

using System;
using System.IO;
using System.IO.Pipes;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("我是程序A");
        Console.WriteLine("---------------------------------------------------------------");

        using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("mypipe"))
        {
            pipeServer.WaitForConnection();

            Random random = new Random();

            while (true)
            {
                try
                {
                    string message = random.Next().ToString();
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(message);

                    pipeServer.Write(buffer, 0, buffer.Length);

                    Console.WriteLine(message);
                    Thread.Sleep(5000);
                }
                catch (IOException ex)
                {
                    // B程序已经关闭,处理异常
                    Console.WriteLine("B程序已经关闭:" + ex.Message);
                    break;
                }
            }
        }
    }
}

程序B

using System;
using System.IO;
using System.IO.Pipes;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("我是程序B");
        Console.WriteLine("---------------------------------------------------------------");

        using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "mypipe", PipeDirection.In))
        {
            try
            {
                pipeClient.Connect();
            }
            catch (Exception ex)
            {
                // A程序已经关闭,处理异常
                Console.WriteLine("A程序已经关闭:" + ex.Message);
                return;
            }

            byte[] buffer = new byte[1024];
            while (true)
            {
                try
                {
                    int bytesRead = pipeClient.Read(buffer, 0, buffer.Length);
                    string message = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);

                    Console.WriteLine(message);
                }
                catch (IOException ex)
                {
                    // A程序已经关闭,处理异常
                    Console.WriteLine("A程序已经关闭:" + ex.Message);
                    break;
                }
            }
        }
    }
}

效果如图

在这里插入图片描述

不懂评论 私信enjoy

在这里插入图片描述
pic from a SHX.

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值