1. 程式人生 > >Unity 打包 讀取Txt檔案視窗初始化(解析度,視窗位置)

Unity 打包 讀取Txt檔案視窗初始化(解析度,視窗位置)

1. Unity 程式視窗初始化指令碼

using System;
using System.Collections;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;

public class RemoveTheGameBorder : MonoBehaviour
{

    public Text text;
    public Text text2;
    [DllImport("user32.dll")]
    static extern IntPtr SetWindowLong(IntPtr hwnd, int _nIndex, int dwNewLong);
    [DllImport("user32.dll")]
    static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();

    const uint SWP_SHOWWINDOW = 0x0040;
    const int GWL_STYLE = -16;  //邊框用的
    const int WS_BORDER = 1;
    const int WS_POPUP = 0x800000;

    // 視窗顯示的位置
    int _posX = 0;
    int _posY = 0;

    // 在這裡設定你想要的視窗寬
    int _Txtwith = 200;
    // 在這裡設定你想要的視窗高
    int _Txtheight = 200;

    // 是否全屏顯示
    bool fullScreenBol = true;
    private void Awake()
    {
        // 是否全屏顯示
        SetFullScreen();
      
        // 根據配置表讀的資料計算出視窗位置	
        SetWindowPos();
      
        // 設定無邊框和位置
        StartCoroutine("Setposition");
    }

    /// <summary>
    ///  全屏顯示
    /// </summary>
    private void SetFullScreen()
    {
        //這個是Unity裡的設定螢幕大小,
        _Txtwith = int.Parse(TxtHandle.TxtReadStr("_Txtwith"));
        _Txtheight = int.Parse(TxtHandle.TxtReadStr("_Txtheight"));
        // 讀取 txt 文字配置表
        if (TxtHandle.TxtReadStr("fullScreenBol").Trim().Equals("true", StringComparison.CurrentCultureIgnoreCase))
        {
            fullScreenBol = true;
        }
        else
        {
            fullScreenBol = false;
        }
        Screen.SetResolution(_Txtwith, _Txtheight, fullScreenBol);
    }

    /// <summary>
    /// 根據配置表讀的資料計算出視窗位置 螢幕中心為 0,0 左上角為(-1,1),以此類推
    /// </summary>
    private void SetWindowPos()
    {
        if (TxtHandle.TxtReadStr("_posXID") == null || TxtHandle.TxtReadStr("_posYID") == null)
        {
            Debug.Log("Txt 文字未讀取成功");
            return;
        }
        int _posXID = int.Parse(TxtHandle.TxtReadStr("_posXID"));
        int _posYID  = int.Parse(TxtHandle.TxtReadStr("_posYID"));
        
        // 使用者不需要去計算螢幕的寬高 (0,-1)(0,0)(0,-1)(1,0)(0,0)...
        switch (_posXID)
        {
            case -1:
                _posX = 0;
                break;
            case 0:
                _posX = Screen.currentResolution.width / 2 - Screen.width/2;
                break;
            case 1:
                _posX = Screen.currentResolution.width - Screen.width;
                break;
            default:
                break;
        }
        switch (_posYID)
        {
            case -1:
                _posY = Screen.currentResolution.height - Screen.height;
                break;
            case 0:
                _posY = Screen.currentResolution.height / 2 - Screen.height/2;
                break;
            case 1:
                _posY = 0;
                break;
            default:
                break;
        }

    }

    /// <summary>
    /// 設定視窗位置和無邊框等
    /// </summary>
    /// <returns></returns>
    IEnumerator Setposition()
    {
        text.text = _posX.ToString();
        text2.text = _posY.ToString();
        yield return new WaitForSeconds(0.1f);		//不知道為什麼釋出於行後,設定位置的不會生效,我延遲0.1秒就可以
        SetWindowLong(GetForegroundWindow(), GWL_STYLE, WS_POPUP);      //無邊框
        bool result = SetWindowPos(GetForegroundWindow(), -1, _posX, _posY, _Txtwith, _Txtheight, SWP_SHOWWINDOW);       //設定螢幕大小和位置
    }
}

2.Txt 讀取類

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;

public class TxtHandle : MonoBehaviour
{
    public static string[] configAry;
    static  List<string> list = new List<string>();
    string txtName = "configuration.txt";
    // Use this for initialization
    void Awake()
    {
        //StartCoroutine(WWWLoadTxtFile("/" + txtName));
        IOLoadTxtFile(txtName);

    }

    /// <summary>
    /// 檔案流讀取Txt檔案
    /// </summary>
    /// <param name="_filePath"></param>
    void IOLoadTxtFile(string _filePath)
    {
        //本地路徑
        var fileAddress = System.IO.Path.Combine(Application.streamingAssetsPath, _filePath);
        FileInfo fInfo0 = new FileInfo(fileAddress);
        string s = "";
        if (fInfo0.Exists)
        {
            StreamReader r = new StreamReader(fileAddress);
            s = r.ReadToEnd();
            configAry = s.Trim().Split(',');
            foreach (var item in configAry)
            {
                list.Add(item);
            }
        }
    }

    /// <summary>
    ///  www類 載入txt檔案
    /// </summary>
    /// <param name="_filePath"></param>
    /// <returns></returns>
    public IEnumerator WWWLoadTxtFile(string _filePath)
    {
      
        print(Application.streamingAssetsPath);
        WWW www = new WWW(Application.streamingAssetsPath + _filePath);
        yield return www;
        if (www.error == null)
        {
            configAry = www.text.ToString().Trim().Split(',');
            foreach (var item in configAry)
            {
                print(item);
            }
            SceneManager.LoadScene(1);
        }
        else
        {
            Debug.Log(www.error);
        }
    }

    /// <summary>
    /// 根據傳過來的 string 返回 該字串在txt檔案中的下一個字串
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string TxtReadStr(string str)
    {
        string tempStr = null;
        if (list.Contains(str))
        {
            for (int i = 0; i < TxtHandle.configAry.Length; i++)
            {
                if (TxtHandle.configAry[i].Trim().Equals(str, StringComparison.CurrentCultureIgnoreCase))
                {
                    tempStr = TxtHandle.configAry[i + 1];
                    break;
                }
            }
        }
        else
        {
            Debug.Log("list not contain" + str);
        }
        return tempStr;
    }

}

3. StreamingAssets 資料夾下 txt 文字內容如下:

4.效果圖如下: