获取Unity3D实例

最近在用JetBrains的Rider在做Unity3D的项目,用起来很舒服,但唯一不好的地方是它的Unity插件检测不到Standalone实例的端口,很是烦人,所以我就自己动手用PowerShell写了这么一个小工具,用来检测端口。这里得到的端口可以直接用来调试Unity3D程序。

获取Unity3D实例_第1张图片

主要代码:

Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms
Import-Module .\Get-NetworkStatistics.ps1
$formTitle = "Unity Instance"
$formPosition = [System.Enum]::GetValues('System.Windows.Forms.FormStartPosition')[1]

$fieldComputerName = "ComputerName"
$fieldProcessName = "ProcessName"
$fieldLocalPort = "LocalPort"

$dataGridView = New-Object System.Windows.Forms.DataGridView
$form = New-Object System.Windows.Forms.Form
$form.add_FormClosing({$timer1.Stop()})

$timer1 = New-Object System.Windows.Forms.Timer
$timer1.Enabled = $true
$timer1.Start()
$timer1.Interval = 5000
$timer1.add_tick({CheckDataGridView})

function GetData
{
    return Get-NetworkStatistics -Computername $env:COMPUTERNAME -Protocol tcp -Address 0.0.0.0 -Port 56* | select $fieldComputerName, $fieldProcessName, $fieldLocalPort 
}

function SetupDataGridView
{
    $dataGridView.ColumnCount = 3
    $dataGridView.AutoSize = $true
    $dataGridView.Columns[0].Name = $fieldComputerName
    $dataGridView.Columns[1].Name = $fieldProcessName
    $dataGridView.Columns[2].Name = $fieldLocalPort

    CheckDataGridView
}

function SetupForm
{
    $form.AutoSize = $true
    $form.StartPosition = $formPosition 
    $form.MaximizeBox = $false
    $form.MinimizeBox = $false
    $form.Controls.Add($dataGridView)
    $form.Text = $formTitle
    $form.ShowDialog() 
}

function CheckDataGridView
{
    $datas = GetData
    $dataGridView.Rows.Clear()
    foreach($data in $datas)
    {
        if($data.ProcessName -ne "Unknown")
        {
            $row = $data.ComputerName, $data.ProcessName, $data.LocalPort 
            $dataGridView.Rows.Add($row) | Out-Null
        }
    }
    $dataGridView.AutoResizeRows()
    $dataGridView.Refresh()
}

function main
{
    SetupDataGridView
    SetupForm
}

main

Github源代码:

Get-UnityInstance

用法:

直接运行Start.bat

注意:

你运行代码的时侯可能会遇到提示PowerShell ExecutePolicy的问题。
你可以在管理员权限的PowerShell命令行里面试试:
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
要是你在使用中遇到问题,也可以通过站内信和我交流。

PowerShell权限参考:

Powershell 编写和运行脚本

你可能感兴趣的:(Unity3D,powershell,unity3d,powershell,调试,rider,c#)