2016年12月28日 星期三

Unity 讀取文字檔內文

VariousVocabularyCreateText(C#):

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

namespace VariousVocabularyCreateText
{

    public class VocabularyData
    {
        // 檔案路徑
        private string folderPath = "D:/Vocabulary/";
        private string folderPathType
        {
            get { return folderPath; }
        }

        // 檔案名稱
        private string vocabularName;
        public string vocabularNameType
        {
            get { return vocabularName; }
            set { vocabularName = value; }
        }

        // 讀取文字檔內文
        private string readtxtMessage;
        public string readtxtMessageType
        {
            get { return readtxtMessage; }
        }

        // 附檔名
        private string attachment = ".txt";

        // 文字內容
        private List readTxtMessageList = new List();

        /// 
        /// 檢查資料夾
        /// 
        /// 
        private bool examinationFolderFunction()
        {

            bool fileExisit = (File.Exists(folderPath)) ? true : false;
            return fileExisit;
        }

        /// 
        /// 檢查文字檔
        /// 
        /// 
        private bool exmainationTxtFunction()
        {

            bool txtFileExisit = (File.Exists(folderPath + vocabularName + attachment)) ? true : false;
            return txtFileExisit;
        }

        /// 
        /// 建立文件檔
        /// 
        public void createTxtMeesage()
        {

            if (!examinationFolderFunction())
            {
                Directory.CreateDirectory(folderPath);

                FileStream fileStream = new FileStream(folderPath + vocabularName + attachment, FileMode.OpenOrCreate);
                StreamWriter stramWrite = new StreamWriter(fileStream);

                try
                {
                    stramWrite.WriteLine("安安");
                    stramWrite.WriteLine("狗狗");
                    stramWrite.Close();
                }
                catch (IOException ex)
                {
                    Debug.Log(ex.Message);
                    return;
                }
            }
        }

        /// 
        /// 讀取文建資料
        /// 
        /// 
        private List readFileTxtMessage()
        {
            StreamReader streamReader = new StreamReader(folderPath + vocabularName + attachment);
            while ((readtxtMessage = streamReader.ReadLine()) != null)
                readTxtMessageList.Add(readtxtMessage);

            streamReader.Close();
            return readTxtMessageList;
        }
    }
}
-----------------------------
 執行腳本(C#): 讀取記事本內文
using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

    VariousVocabularyCreateText.VocabularyData vocabularData = new VariousVocabularyCreateText.VocabularyData();

    void Start() {

        vocabularData.vocabularNameType = "bb";

        foreach (string message in vocabularData.readFileTxtMessage())
        {
            Debug.Log(message);
        }
    }
}
-----------------------------
 執行腳本(C#): 建立文建及換行
using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

    VariousVocabularyCreateText.VocabularyData vocabularData = new VariousVocabularyCreateText.VocabularyData();

    void Start() {
        vocabularData.vocabularNameType = "bb";
        vocabularData.createTxtMeesage();
    }
}

2016年11月2日 星期三

九宮格-拼圖遊戲-小品遊戲 (結束)

本文是九宮格拼圖遊戲-小品遊戲

圖片分割程式碼(請點選文字超連結)

腳本對印圖:



























圖片分割數量:




















結果圖:


 ----------------
開始遊戲九宮格圖片亂數變化 Script(C#):

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[RequireComponent(typeof(DetectionObjcet))]
[RequireComponent(typeof(MoveImage))]
[RequireComponent(typeof(Gamesettlement))]
public class Jiugongge : MonoBehaviour
{
    public Sprite[] sprite = new Sprite[8];                                  // 預設圖片
    private int type = 9;                                    // 建立物件數量

    public List objcetList = new List();   // list 監管物件建立
    private GameObject spriteMaster;                        // sprite 管理物件
    private BoxCollider boxCollider;                        // Sprite Collider;

    private bool randomSw = false;                          // 亂數開關
    private int randomNumber;                               // 亂數
    private int limitObjcet = 0;                            // 限制物件

    private List numbers = new List();

    // Use this for initialization
    void Awake()
    {
        spriteMaster = new GameObject("SpriteMaster");  // sprite  管理
        spriteMaster.transform.position = Vector2.zero; // sprite 管理位置

        spriteSwitch();
    }

    /// 
    /// 視窗GUI
    /// 
    void OnGUI()
    {
        randomSw = (GUI.Button(new Rect(Screen.width / Screen.width, Screen.height / Screen.height, 100, 30), "拼圖重製")) ? true : false;

        if (randomSw.Equals(true))
        {
            //  notRepeatingRandom();
            Application.LoadLevel("aa");

        }
    }

    /// 
    /// 加入圖片亂數選擇
    /// 
    void spriteSwitch()
    {
        randomNumberListWithoutDuplicate(type);

        while (limitObjcet < type)
        {
            try
            {

                randomNumber = getNumberInList();

                createSprite().GetComponent().sprite = sprite[randomNumber];
            }
            catch
            {
                Debug.LogError("警告");
            }
            limitObjcet++;
        }
        show();
    }

    /// 
    /// 選取範圍
    /// 
    int getNumberInList()
    {
        int return_num = numbers[0];
        numbers.RemoveRange(0, 1);
        return return_num;
    }

    /// 
    /// 亂數排序
    /// 
    List randomNumberListWithoutDuplicate(int max)
    {

        for (int i = 0; i < max; i++)
            numbers.Add(i);


        for (int i = 0; i < numbers.Count; i++)
        {
            int temp = numbers[i];
            int randomIndex = Random.Range(i, numbers.Count);
            numbers[i] = numbers[randomIndex];
            numbers[randomIndex] = temp;
        }

        return numbers;
    }

    /// 
    /// objcet 位置
    /// 
    void show()
    {

        int objcetNumber = 0;

        foreach (GameObject objcet in objcetList)
        {
            objcetNumber += 1;
            objcet.transform.SetParent(spriteMaster.transform);
            objcet.name = "Image" + objcetNumber;

            switch (objcetNumber)
            {
                case 1:
                    objcet.transform.position = new Vector2(-3.4f, 0);
                    break;
                case 2:
                    objcet.transform.position = new Vector2(-3.4f, 3.4f);
                    break;
                case 3:
                    objcet.transform.position = new Vector2(-3.4f, 6.8f);
                    break;
                case 4:
                    objcet.transform.position = new Vector2(0, 0);
                    break;
                case 5:
                    objcet.transform.position = new Vector2(0, 3.4f);
                    break;
                case 6:
                    objcet.transform.position = new Vector2(0, 6.8f);
                    break;
                case 7:
                    objcet.transform.position = new Vector2(3.4f, 0f);
                    break;
                case 8:
                    objcet.transform.position = new Vector2(3.4f, 3.4f);
                    break;
                case 9:
                    objcet.transform.position = new Vector2(3.4f, 6.8f);
                    break;
            }
        }
    }

    /// 
    /// 建立物件
    /// 
    /// 
    GameObject createSprite()
    {

        GameObject objcet = new GameObject("Image");

        objcetAddComponentFunction(objcet);
        ComponentSetting();

        objcetList.Add(objcet);
        return objcet;
    }

    /// 
    /// 物件加入組件
    /// 
    /// 
    void objcetAddComponentFunction(GameObject objcet)
    {
        objcet.AddComponent();
        boxCollider = objcet.AddComponent();
    }

    /// 
    /// 組件設定
    /// 
    void ComponentSetting()
    {
        boxCollider.size = new Vector3(3.4f, 3.4f, 0);
    }
}

---------------
Script(c#) 偵測方位物件
using UnityEngine;
using System.Collections;

public class DetectionObjcet : MonoBehaviour {

    private Jiugongge jiugongge;                    // 九宮格腳本
    private Ray ray1, ray2, ray3, ray4;             // 射線
    private RaycastHit hits1, hits2, hits3, hits4;  // 射線碰撞

    public GameObject objcetSprtieNull;             // 沒貼圖片物件
    public GameObject leftMoveObjcet,               // 射線偵測左邊物件
                      rightMoveObjcet,              // 射線偵測右邊物件
                      upMoveObjcet,                 // 射線偵測上邊物件
                      downMoveObjcet;               // 射線偵測下邊物件

    void Awake()
    {   
        jiugongge = gameObject.GetComponent();   // 取得物件腳本
        readOjbcetNoSprite();             
    }

    void Update()
    {
        RayColliderObjcet();

        // 射線方位
        ray1 = leftRayPoint();
        ray2 = rightRayPoint();
        ray3 = upRayPoint();
        ray4 = downRayPoint();
    }

    /// 
    /// 射線偵測
    /// 
    void RayColliderObjcet() {

        if (Physics.Raycast(ray1, out hits1))
            leftMoveObjcet = hits1.collider.gameObject;

        if (Physics.Raycast(ray2, out hits2))
            rightMoveObjcet = hits2.collider.gameObject;


        if (Physics.Raycast(ray3, out hits3))
            upMoveObjcet = hits3.collider.gameObject;

        if (Physics.Raycast(ray4, out hits4))
            downMoveObjcet = hits4.collider.gameObject;
    }

    /// 
    ///  左邊射線
    /// 
    /// 
    Ray leftRayPoint() {

        Vector2 vector2 = objcetSprtieNull.transform.position;

        Ray ray = new Ray(vector2, Vector2.left);
        return ray;
    }

    /// 
    /// 右邊射線
    /// 
    /// 
    Ray rightRayPoint()
    {
        Vector2 vector2 = objcetSprtieNull.transform.position;

        Ray ray = new Ray(vector2, Vector2.right);

        return ray;
    }

    /// 
    /// 向上射線
    /// 
    /// 
    Ray upRayPoint()
    {
        Vector2 vector2 = objcetSprtieNull.transform.position;

        Ray ray = new Ray(vector2, Vector2.up);

        return ray;
    }

    /// 
    /// 向下射線
    /// 
    /// 
    Ray downRayPoint()
    {
        Vector2 vector2 = objcetSprtieNull.transform.position;

        Ray ray = new Ray(vector2, Vector2.down);

        return ray;

    }

    /// 
    /// 尋找沒貼圖物件
    /// 
    void readOjbcetNoSprite()
    {
        foreach (GameObject objcet in jiugongge.objcetList)
        {
            if (objcet.GetComponent().sprite == null)
                objcetSprtieNull = objcet;
        }
    }
}

--------------------
偵測物件並且與沒有貼圖物件位置對調
using UnityEngine;
using System.Collections;

public class MoveImage : MonoBehaviour {

    private DetectionObjcet detectionObjcet;        // 選擇物件類別
 
    private Ray userRay;                            // 玩家射線
    private RaycastHit userRayHits;                 // 射線碰撞

    private Vector2 moveLimitPoint,                 // 無Sprite 物件位置(交換位置)
                    clickObjcetPoint;               // 射線探聽物件位置

    void Awake() {

        detectionObjcet = GetComponent();
    }

    void Update(){

        userRayFunction();
    }

    /// 
    /// 玩家發出射線 (可更改控制事件)
    /// 
    void userRayFunction() {

        userRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        moveLimitPoint = detectionObjcet.objcetSprtieNull.transform.position;

        if (Input.GetMouseButton(0))
        {
            if (Physics.Raycast(userRay, out userRayHits))
            {
                GameObject userOnclickObjcet = userRayHits.collider.gameObject;

                OnClickView(userOnclickObjcet);
            }
        }
    }

    /// 
    /// 探聽事件
    /// 
    /// 
    void OnClickView(GameObject objcet)
    {
        if (objcet == detectionObjcet.leftMoveObjcet)
        {
            clickObjcetPoint = objcet.transform.position;
            MoveObjcetFunction_Left(detectionObjcet.leftMoveObjcet, moveLimitPoint);
        }

        if (objcet == detectionObjcet.rightMoveObjcet)
        {
            clickObjcetPoint = objcet.transform.position;
            MoveObjcetFunction_Right(detectionObjcet.rightMoveObjcet, moveLimitPoint);
        }

        if (objcet == detectionObjcet.upMoveObjcet)
        {
            clickObjcetPoint = objcet.transform.position;
            MoveObjcetFunction_Up(detectionObjcet.upMoveObjcet, moveLimitPoint);
        }


        if (objcet == detectionObjcet.downMoveObjcet)
        {
            clickObjcetPoint = objcet.transform.position;
            MoveObjcetFunction_Down(detectionObjcet.downMoveObjcet, moveLimitPoint);
        }
    }

    /// 
    /// 偵測左邊物件_向右移動
    /// 
    /// 
    /// 
    void MoveObjcetFunction_Left(GameObject objcet, Vector2 point) {
  
        if(objcet.transform.position.x <= point.x)
        {
            objcet.transform.position = new Vector2(point.x, point.y);
        }
        detectionObjcet.objcetSprtieNull.transform.position = clickObjcetPoint;
    }

    /// 
    /// 偵測右邊物件_向左移動
    /// 
    /// 
    /// 
    void MoveObjcetFunction_Right(GameObject objcet, Vector2 point) {

        if (objcet.transform.position.x >= point.x)
        {
            objcet.transform.position = new Vector2(point.x, point.y);
        }
        detectionObjcet.objcetSprtieNull.transform.position = clickObjcetPoint;
    }

    /// 
    /// 偵測上邊物件_向下移動
    /// 
    /// 
    /// 
    void MoveObjcetFunction_Up(GameObject objcet, Vector2 point) {

        if (objcet.transform.position.y >= point.y)
        {
            objcet.transform.position = new Vector2(point.x, point.y);
        }
        detectionObjcet.objcetSprtieNull.transform.position = clickObjcetPoint;
    }


    /// 
    /// 偵測下邊物件_向上移動
    /// 
    /// 
    /// 
    void MoveObjcetFunction_Down(GameObject objcet, Vector2 point) {

        if (objcet.transform.position.y <= point.y)
        {
            objcet.transform.position = new Vector2(point.x, point.y);
        }
        detectionObjcet.objcetSprtieNull.transform.position = clickObjcetPoint;
    }
}

---------------------
遊戲結算(輸贏/其他方式結束遊戲) ※ 本程式只判斷遊戲是否拼圖正確
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Gamesettlement : MonoBehaviour
{

    private DetectionObjcet detctionObjcet;     // 選擇物件類別
    private Jiugongge jiugongge;                // 取得最先設定類別

    public Sprite winSprite;                    // 補區塊

    private bool win;                           // 輸贏數值

    void Awake()
    {

        detctionObjcet = GetComponent();
        jiugongge = GetComponent();
    }

    void Update()
    {

        readObjcetSprtie();

        if(win)
            detctionObjcet.objcetSprtieNull.GetComponent().sprite = winSprite;

        Debug.Log(win);
    }

    void OnGUI() {

        string str = (win.Equals(true)) ? "完成" : "未完成";

        GUI.Label(new Rect(Screen.width / Screen.width, Screen.height / Screen.height * 30f, 300, 30), str);

        if (Input.GetKey(KeyCode.Escape))
        {
            Application.Quit();
        }
    }

    /// 
    /// 讀取物件Sprite後及判斷位置
    /// 
    void readObjcetSprtie()
    {

        bool point1 = false, point2 = false, point3 = false, point4 = false, point5 = false, point6 = false,
            point7 = false, point8 = false;

        foreach (GameObject objcet in jiugongge.objcetList)
        {
            try
            {
                // sprite1 位置 x:-3.4f, y:0f;
                if (objcet.GetComponent().sprite.Equals(jiugongge.sprite[0]))
                {
                    if (objcet.transform.position.x.Equals(-3.4f) & objcet.transform.position.y.Equals(0))
                        point1 = true;
                }

                // sprite2 位置 x:-3.4f, y:3.4f;
                if (objcet.GetComponent().sprite.Equals(jiugongge.sprite[1]))
                {
                    if (objcet.transform.position.x.Equals(-3.4f) & objcet.transform.position.y.Equals(3.4f))
                        point2 = true;
                }

                // sprite3 位置 x:-3.4f, y:6.8f;
                if (objcet.GetComponent().sprite.Equals(jiugongge.sprite[2]))
                {
                    if (objcet.transform.position.x.Equals(-3.4f) & objcet.transform.position.y.Equals(6.8f))
                        point3 = true;
                }

                // sprite4 位置 x:0f, y:0f;
                if (objcet.GetComponent().sprite.Equals(jiugongge.sprite[3]))
                {
                    if (objcet.transform.position.x.Equals(0) & objcet.transform.position.y.Equals(0))
                        point4 = true;
                }

                // sprite5 位置 x:0f, y:3.4f;
                if (objcet.GetComponent().sprite.Equals(jiugongge.sprite[4]))
                {
                    if (objcet.transform.position.x.Equals(0) & objcet.transform.position.y.Equals(3.4f))
                        point5 = true;
                }

                // sprite6 位置 x:0f, y:6.8f;
                if (objcet.GetComponent().sprite.Equals(jiugongge.sprite[5]))
                {
                    if (objcet.transform.position.x.Equals(0) & objcet.transform.position.y.Equals(6.8f))
                        point6 = true;
                }

                // sprite7 位置 x:3.4f, y:0f;
                if (objcet.GetComponent().sprite.Equals(jiugongge.sprite[6]))
                {
                    if (objcet.transform.position.x.Equals(3.4f) & objcet.transform.position.y.Equals(0))
                        point7 = true;
                }

                // sprite8 位置 x:3.4f, y:3.4f;
                if (objcet.GetComponent().sprite.Equals(jiugongge.sprite[7]))
                {
                    if (objcet.transform.position.x.Equals(3.4f) & objcet.transform.position.y.Equals(3.4f))
                        point8 = true;
                }
            }
            catch
            {
                Debug.LogError("警告2: 強迫語法");
            }
        }

        // point 1-8 正確就可以過關
        if (point1 & point2.Equals(true) & point3.Equals(true) & point4.Equals(true) & point5.Equals(true)
            & point6.Equals(true) & point7.Equals(true) & point8.Equals(true))
            win = true;
        else win = false;
    }
}

2016年10月28日 星期五

Unity 編輯視窗方割Sprite

小弟我之前跟夥伴一起做過遊戲,因為我負責程式部分,主要原因我程式控制Sprite組件為主,導致要去進行所謂的分割,但是發現到另外夥伴對於美術所繪製的人物位置太過於隨意,導致成是這邊最後還要去進行最後調整,浪費了許多時間。

因此就想要試做,如何可以分割Sprite 裡面的小圖片,所寫的程式,小弟程式功力不是很好希望各位大大,有更好的方式,也歡迎提供。

--------------
Script(c#):

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;

public class SpriteProcessor : EditorWindow
{

    private Vector2 vector2Label;          // 標籤位置(BeginScrollView 用的)
    private GUIStyle style = new GUIStyle();   // GUI 風格
    private string spriteSegmentationType = "";  // Sprite 分割像素
    private string spriteName = "";        // Sprite 分格後名稱
    private int spriteTitleNumber = 0;   // 分格後的名稱編號
    private int spriteSegmentationNumber;   // 分割數值字串轉型


    /// 
    ///  呼叫視窗
    /// 
    [MenuItem("測試/Sprite寫法")]
    public static void spriteWindowSetting()
    {
        SpriteProcessor windows = EditorWindow.GetWindow(typeof(SpriteProcessor), true, "Sprite 自動分割") as SpriteProcessor;
        windows.Show();
    }

    /// 
    /// 選擇貼圖(Sprite)
    /// 
    /// 
    static Object[] getSelectTexture()
    {
        return Selection.GetFiltered(typeof(Texture2D), SelectionMode.DeepAssets);
    }

    void OnGUI()
    {

        style.fontSize = 18;
        style.normal.textColor = Color.white;

        GUI.Label(new Rect(0, 0, 100, 30), "圖片分割", style);

        // Sprite 分割像素
        GUILayout.BeginArea(new Rect(0, 30, 300, 100));
        GUILayout.BeginHorizontal();
        GUILayout.Label("Sprite 分割像素");
        GUILayout.EndHorizontal();
        GUILayout.EndArea();

        // Sprite 分割像素輸入
        GUILayout.BeginArea(new Rect(150, 30, 150, 100));
        GUILayout.BeginHorizontal();
        spriteSegmentationType = GUILayout.TextField(spriteSegmentationType);
        GUILayout.EndHorizontal();
        GUILayout.EndArea();

        // Sprite標籤
        GUILayout.BeginArea(new Rect(0, 110, 300, 100));
        GUILayout.BeginHorizontal();
        GUILayout.Label("Sprite 標簽名稱");
        GUILayout.EndArea();
        GUILayout.EndHorizontal();

        // Sprite標籤輸入
        GUILayout.BeginArea(new Rect(148, 110, 150, 100));
        GUILayout.BeginHorizontal();
        spriteName = GUILayout.TextField(spriteName);
        GUILayout.EndHorizontal();
        GUILayout.EndArea();

        GUILayout.BeginArea(new Rect(200, 150, 100, 100));
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("確定"))
            SetPivots();
        GUILayout.EndHorizontal();
        GUILayout.EndArea();
    }

    /// 
    /// 分割動作
    /// 
    void SetPivots()
    {
        spriteTitleNumber = 0;
        // 判斷轉型成功執行分割
        if (int.TryParse(spriteSegmentationType, out spriteSegmentationNumber))
        {
            Object[] textures = getSelectTexture();
            Selection.objects = new Object[0];

            SpriteMetaData d = new SpriteMetaData();
            
            foreach (Texture2D texture in textures)
            {
                string path = AssetDatabase.GetAssetPath(texture);
                TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter;
                ti.isReadable = true;
                List<SpriteMetaData> newData = new List<SpriteMetaData>();
                newData.Remove(d);
                for (int x = 0; x < texture.width; x += spriteSegmentationNumber)
                {
                    for (int y = 0; y < texture.height; y += spriteSegmentationNumber)
                    {
                        d.alignment = 9;
                        d.pivot = new Vector2(0.5f, 0.5f);
                        d.name = spriteName + "_" + (spriteTitleNumber += 1);
                        d.rect = new Rect(x, y, spriteSegmentationNumber, spriteSegmentationNumber);
                        newData.Add(d);
                    }
                }
                ti.spritesheet = newData.ToArray();
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
            }
        }
    }
}

------------
 結果圖:

2016年10月3日 星期一

Blender 匯入fbx錯誤...解決方法

Blender 如果匯入fbx 錯誤,會出現這個訊息: Version 6100 unsupported, must be 7100 or later







爬文之後,證明是fbx SDK的問題,小弟這邊解決方法是去下載 Autodesk FBX Converter.之後就可以解決此問題。

有人提供 : fbx sdk 下載地點(AutoDesk) : FBX SDK     感謝 Deathicon 大大提供

點 Add FBX Converter → Add 所需fbx檔案

軟體會重新匯入新的fbx→再由Blender 匯入即可。





2016年9月23日 星期五

Unity 模型觀看別的物件

Unity 官方程式API 也是同樣功能 LookAt (在transform.LookAt(gameobjcet.transform));
------------------

Script(c#):
public class PlasmaData : MonoBehaviour {

    // 物件觀看
    public void lookAtObjcet(GameObject lookOjcet, GameObject meOjcet) {

        Vector3 vec = meOjcet.transform.position - lookOjcet.transform.position;
        Quaternion rota = Quaternion.LookRotation(new Vector3(-vec.x, -vec.y, -vec.z));
        float angle = Quaternion.Angle(rota, Quaternion.identity);

        meOjcet.transform.rotation = Quaternion.Lerp(meOjcet.transform.rotation, rota, 0.2f);
         
     
    }
}

------------------

更新程式碼 ( 功能含 射程範圍、限制物件旋轉角度)

Script(c#):

using UnityEngine;
using System.Collections;

public class CannonData : MonoBehaviour {

    // 我方觀看物件
    private GameObject lookOjcetType;
    public GameObject lookObjcet {
        get { return lookOjcetType; }
        set { lookOjcetType = value; }
    }

    // 我方自己物件
    private GameObject meOjcetType;
    public GameObject meOjcet {
        get { return meOjcetType; }
        set { meOjcetType = value; }
    }

    // 我方選轉角度
    private float rotationAngleTpye;
    public float rotationAngle {
        get { return rotationAngleTpye; }
        set { rotationAngleTpye = value; }
    }

    // 我方射程範圍
    private float rangeType;
    public float range {
        get { return rangeType; }
        set { rangeType = value; }
    }

    // 選擇正與反向
    private int modeType;
    public int mode {
        get { return modeType; }
        set { modeType = value; }
    }

     public void LookAtFouction() {

        switch (modeType) {

            case 1:

                if (Vector3.Distance(lookOjcetType.transform.position, meOjcetType.transform.position) < rangeType) {                 
                    // 計算向量,目標座標 - 自己自身座標
                    Vector3 vec = lookOjcetType.transform.position - meOjcetType.transform.position;
                    // 降量轉為四元素即旋轉值
                    Quaternion rota = Quaternion.LookRotation(new Vector3(-vec.x, -vec.y, -vec.z));
                    // 計算rota與自身旋轉角度的夾角,在此砲台的默認選轉設為 Quaternion.identity
                    float angle = Quaternion.Angle(rota, Quaternion.identity);

                    if (angle > rotationAngleTpye * 0.5f)
                    {
                        meOjcetType.transform.rotation = Quaternion.Lerp(meOjcetType.transform.rotation, rota, 0.2f);
                        Debug.DrawLine(meOjcetType.transform.position, lookOjcetType.transform.position, Color.red);
                    }
                }
                
                break;

           case 2:

                if (Vector3.Distance(lookOjcetType.transform.position, meOjcetType.transform.position) < rangeType)
                {
                    Vector3 vec2 = lookOjcetType.transform.position - meOjcetType.transform.position;
                    Quaternion rota2 = Quaternion.LookRotation(vec2);
                    float angle2 = Quaternion.Angle(rota2, Quaternion.identity);

                    if (angle2 > rotationAngleTpye * 0.5f)
                    {
                        meOjcetType.transform.rotation = Quaternion.Lerp(meOjcetType.transform.rotation, rota2, 0.2f);
                        Debug.DrawLine(meOjcetType.transform.position, lookOjcetType.transform.position, Color.red);
                    }
                }
                break;
        }
    }

}

-----------------------

使用方式-說明:

利用物件裡面的程式加入Component記得在Awake方法呼叫,如果使用Update 方式呼叫很吃效能,也可以寫在Start裡面呼叫,但是小弟並不建議就是了。

Script(c#) :

using UnityEngine;
using System.Collections;

public class PlasmaFunction : PlasmaData{

    public GameObject[] door, charged;
    public float x = 327, speed = 5;
    public GameObject enemy, barrel;  // 敵人, 自己

    public float rotationAngle;  // 大砲選轉角度
    public float range;         // 射程
    public int mode;            // 大砲選轉模式

    CannonData cannon;

    void Awake() {

        cannon = gameObject.AddComponent<CannonData>();
        cannon.lookObjcet = enemy;
        cannon.meOjcet = barrel;
        cannon.rotationAngle = rotationAngle;
        cannon.range = range;
        cannon.mode = mode;
    }


    void Update(){

        cannon.LookAtFouction();
    }
}

2016年9月6日 星期二

Unity在Asset 路徑取得貼圖在設定腳本

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;

public class SpriteFunction : EditorWindow{

    static void Init() {
        SpriteFunction winodws = (SpriteFunction)EditorWindow.GetWindow(typeof(SpriteFunction),true, "sprite 方法");
        winodws.Show();
    }


    TextureImporter getTextureSetting(string path) {
        TextureImporter importes = AssetImporter.GetAtPath(path) as TextureImporter;
        // 貼圖設定功能
        return importes;
    }

    void loopSetTexture() {

        Object[] textures = getSelectTexture2D();
        Selection.objects = new Object[0];

        foreach (Texture2D texture in textures) {
            string path = AssetDatabase.GetAssetPath(texture);
            TextureImporter texImporter = getTextureSetting(path);
            TextureImporterSettings tis = new TextureImporterSettings();
            texImporter.ReadTextureSettings(tis);
            texImporter.SetTextureSettings(tis);
            AssetDatabase.ImportAsset(path);

        }
    }

    /// <summary>
    /// 選取貼圖
    /// </summary>
    /// <returns></returns>
    Object[] getSelectTexture2D() {
        return Selection.GetFiltered(typeof(Texture2D), SelectionMode.DeepAssets);
    }
}

2016年9月3日 星期六

Unity3D 圖片資源匯入設置

Script (c#):

using UnityEngine;
using System.Collections;
using UnityEditor;
/// <summary>
/// 批量图片资源导入设置
/// 使用说明: 选择需要批量设置的贴图,
/// 单击DuanMenu/Texture Import Settings,
/// 打开窗口后选择对应参数,
/// 点击Set Texture ImportSettings,
/// 稍等片刻,--批量设置成功。
/// </summary>


public class TextureImportSetting : EditorWindow
{

    /// <summary>
    /// 临时存储int[]
    /// </summary>
    private int[] IntArray = new int[] { 0, 1, 2, 3, 4, 5, 6, 7 };
    //AnisoLevel
    private int AnisoLevel = 1;
    //Filter Mode
    private int FilterModeInt = 0;
    private string[] FilterModeString = new string[] { "Point", "Bilinear", "Trilinear" };
    //Wrap Mode
    private int WrapModeInt = 0;
    private string[] WrapModeString = new string[] { "Repeat", "Clamp" };
    //Texture Type
    private int TextureTypeInt = 0;
    private string[] TextureTypeString = new string[] { "Texture", "Normal Map", "GUI", "Refelection", "Cookie", "Lightmap", "Advanced" };
    //Max Size
    private int MaxSizeInt = 5;
    private string[] MaxSizeString = new string[] { "32", "64", "128", "256", "512", "1024", "2048", "4096" };
    //Format
    private int FormatInt = 0;
    private string[] FormatString = new string[] { "Compressed", "16 bits", "true color" };

    /// <summary>
    /// 创建、显示窗体
    /// </summary>
    [@MenuItem("DuanMenu/Texture Import Settings")]
    private static void Init()
    {
        TextureImportSetting window = (TextureImportSetting)EditorWindow.GetWindow(typeof(TextureImportSetting), true, "TextureImportSetting");
        window.Show();
    }

    /// <summary>
    /// 显示窗体里面的内容
    /// </summary>
    private void OnGUI()
    {
        //AnisoLevel
        GUILayout.BeginHorizontal();
        GUILayout.Label("Aniso Level  ");
        AnisoLevel = EditorGUILayout.IntSlider(AnisoLevel, 0, 9);
        GUILayout.EndHorizontal();
        //Filter Mode
        FilterModeInt = EditorGUILayout.IntPopup("Filter Mode", FilterModeInt, FilterModeString, IntArray);
        //Wrap Mode
        WrapModeInt = EditorGUILayout.IntPopup("Wrap Mode", WrapModeInt, WrapModeString, IntArray);
        //Texture Type
        TextureTypeInt = EditorGUILayout.IntPopup("Texture Type", TextureTypeInt, TextureTypeString, IntArray);
        //Max Size
        MaxSizeInt = EditorGUILayout.IntPopup("Max Size", MaxSizeInt, MaxSizeString, IntArray);
        //Format
        FormatInt = EditorGUILayout.IntPopup("Format", FormatInt, FormatString, IntArray);
        if (GUILayout.Button("Set Texture ImportSettings"))
            LoopSetTexture();
    }

    /// <summary>
    /// 获取贴图设置
    /// </summary>
    public TextureImporter GetTextureSettings(string path)
    {
        TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
        //AnisoLevel
        textureImporter.anisoLevel = AnisoLevel;
        //Filter Mode
        switch (FilterModeInt)
        {
            case 0:
                textureImporter.filterMode = FilterMode.Point;
                break;
            case 1:
                textureImporter.filterMode = FilterMode.Bilinear;
                break;
            case 2:
                textureImporter.filterMode = FilterMode.Trilinear;
                break;
        }
        //Wrap Mode
        switch (WrapModeInt)
        {
            case 0:
                textureImporter.wrapMode = TextureWrapMode.Repeat;
                break;
            case 1:
                textureImporter.wrapMode = TextureWrapMode.Clamp;
                break;
        }
        //Texture Type
        switch (TextureTypeInt)
        {
            case 0:
                textureImporter.textureType = TextureImporterType.Image;
                break;
            case 1:
                textureImporter.textureType = TextureImporterType.Bump;
                break;
            case 2:
                textureImporter.textureType = TextureImporterType.GUI;
                break;
            case 3:
                textureImporter.textureType = TextureImporterType.Reflection;
                break;
            case 4:
                textureImporter.textureType = TextureImporterType.Cookie;
                break;
            case 5:
                textureImporter.textureType = TextureImporterType.Lightmap;
                break;
            case 6:
                textureImporter.textureType = TextureImporterType.Advanced;
                break;
        }
        //Max Size 
        switch (MaxSizeInt)
        {
            case 0:
                textureImporter.maxTextureSize = 32;
                break;
            case 1:
                textureImporter.maxTextureSize = 64;
                break;
            case 2:
                textureImporter.maxTextureSize = 128;
                break;
            case 3:
                textureImporter.maxTextureSize = 256;
                break;
            case 4:
                textureImporter.maxTextureSize = 512;
                break;
            case 5:
                textureImporter.maxTextureSize = 1024;
                break;
            case 6:
                textureImporter.maxTextureSize = 2048;
                break;
            case 7:
                textureImporter.maxTextureSize = 4096;
                break;
        }
        //Format
        switch (FormatInt)
        {
            case 0:
                textureImporter.textureFormat = TextureImporterFormat.AutomaticCompressed;
                break;
            case 1:
                textureImporter.textureFormat = TextureImporterFormat.Automatic16bit;
                break;
            case 2:
                textureImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor;
                break;
        }
        return textureImporter;
    }

    /// <summary>
    /// 循环设置选择的贴图
    /// </summary>
    private void LoopSetTexture()
    {
        Object[] textures = GetSelectedTextures();
        Selection.objects = new Object[0];
        foreach (Texture2D texture in textures)
        {
            string path = AssetDatabase.GetAssetPath(texture);
            TextureImporter texImporter = GetTextureSettings(path);
            TextureImporterSettings tis = new TextureImporterSettings();
            texImporter.ReadTextureSettings(tis);
            texImporter.SetTextureSettings(tis);
            AssetDatabase.ImportAsset(path);
        }
    }

    /// <summary>
    /// 获取选择的贴图
    /// </summary>
    /// <returns></returns>
    private Object[] GetSelectedTextures()
    {
        return Selection.GetFiltered(typeof(Texture2D), SelectionMode.DeepAssets);
    }
}

--------------

資料來源: http://www.cnblogs.com/fortomorrow/archive/2012/11/05/unity11.html

-------------------

更改後版本... 

但是 Unity Editor 還是有很多不足的地方,如: 由 Editor Windows 開啟 Sprite Editor 可能就沒有辦法囉,因為目前小弟暫時找不到方法可以解決。

Script(C#):

using UnityEngine;
using System.Collections;
using UnityEditor;

public class ImportSetting : EditorWindow{

    private int[] intArray = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    private int anisoLevel = 1;

    private int filterModeInt = 0;
    private string[] filterModeString = new string[] { "Point", "Bilinear", "Trilinear" };

    private int wrapModeInt = 0;
    private string[] warpModeSering = new string[] { "Repeat", "Clamp" };

    private int textrueTypeInt = 0;
    private string[] textrueTypeSetting = new string[] { "Textrue", "Normal Map", "GUI", "Refelection", "Cookie", "Lightmap", "Sprite", "Advanced" };

    private int maxSizeInt = 0;
    private string[] maxSizeString = new string[] { "32", "64", "128", "256", "512", "1024", "2048", "4096" };

    private int formatInt = 0;
    private string[] formatString = new string[] { "Compressed", "16 bits", "true color" };

    // Texture 和 Cookie
    private bool alphaFromGraycal = false, alphaIsTransparen = false;

    // Sprite
    private int spriteModeInt = 0;
    private string[] spriteModeString = new string[] { "Single", "Multiple" };
    private string packingTag = "";
    private float pixelsPerUnit = 0;

    GUIStyle style = new GUIStyle();

    [MenuItem("遊戲控制器視窗/匯入素材設定視窗")]
    static void Init() {
        ImportSetting windows = (ImportSetting)EditorWindow.GetWindow(typeof(ImportSetting), true, "素材控制視窗");
        windows.Show();
    }

    void OnGUI() {

        style.fontSize = 18;
        style.normal.textColor = Color.white;

        // Texture Type;
        GUILayout.BeginArea(new Rect(0, 0, 300, 100));
        GUILayout.BeginHorizontal();
        textrueTypeInt = EditorGUILayout.IntPopup("Texture Type(紋理屬性)", textrueTypeInt, textrueTypeSetting, intArray);
        GUILayout.EndHorizontal();
        GUILayout.EndArea();

        GUILayout.BeginArea(new Rect(0, 30, 300, 30));
        GUILayout.BeginHorizontal();
        GUILayout.Label("紋理基本設定設定", style);
        GUILayout.EndHorizontal();
        GUILayout.EndArea();

        // Filter Mode
        GUILayout.BeginArea(new Rect(0, 60, 300, 100));
        GUILayout.BeginHorizontal();
        filterModeInt = EditorGUILayout.IntPopup("Filter Mode(過濾模式)", filterModeInt, filterModeString, intArray);
        GUILayout.EndHorizontal();
        GUILayout.EndArea();

        // Warp Mode
        GUILayout.BeginArea(new Rect(0, 90, 300, 100));
        GUILayout.BeginHorizontal();
        wrapModeInt = EditorGUILayout.IntPopup("Wrap Mode(換行模式)", wrapModeInt, warpModeSering, intArray);
        GUILayout.EndHorizontal();
        GUILayout.EndArea();

        //Max Size
        GUILayout.BeginArea(new Rect(0, 120, 300, 100));
        GUILayout.BeginHorizontal();
        maxSizeInt = EditorGUILayout.IntPopup("Max Size(最大纹理大小)", maxSizeInt, maxSizeString, intArray);
        GUILayout.EndHorizontal();
        GUILayout.EndArea();

        // Format
        GUILayout.BeginArea(new Rect(0, 150, 300, 100));
        GUILayout.BeginHorizontal();
        formatInt = EditorGUILayout.IntPopup("Max Size(紋理格式)", formatInt, formatString, intArray);
        GUILayout.EndHorizontal();
        GUILayout.EndArea();

        // AnisoLevel
        GUILayout.BeginArea(new Rect(0, 180, 300, 100));
        GUILayout.BeginHorizontal();
        GUILayout.Label("AnisoLevel(紋理的過濾等級)");
        anisoLevel = EditorGUILayout.IntSlider(anisoLevel, 0, 9);
        GUILayout.EndHorizontal();
        GUILayout.EndArea();

        // 確定
        GUILayout.BeginArea(new Rect(200, 300, 100, 100));
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("確定"))
            loopSetTexture();
        GUILayout.EndHorizontal();
        GUILayout.EndArea();

        switch (textrueTypeInt) {
  
            case 0:
                
                GUILayout.BeginArea(new Rect(0, 210, 300, 100));
                GUILayout.BeginHorizontal();
                GUILayout.Label("Alpha From Graycal(阿爾法從灰度)");
                alphaFromGraycal = EditorGUILayout.Toggle(alphaFromGraycal);
                GUILayout.EndHorizontal();
                GUILayout.EndArea();

                GUILayout.BeginArea(new Rect(0, 240, 300, 100));
                GUILayout.BeginHorizontal();
                GUILayout.Label("Alpha Is Transparen(阿爾法是透明的)");
                alphaIsTransparen = EditorGUILayout.Toggle(alphaIsTransparen);
                GUILayout.EndHorizontal();
                GUILayout.EndArea();

                break;

            case 4:

                GUILayout.BeginArea(new Rect(0, 210, 300, 100));
                GUILayout.BeginHorizontal();
                GUILayout.Label("Alpha From Graycal(阿爾法從灰度)");
                alphaFromGraycal = EditorGUILayout.Toggle(alphaFromGraycal);
                GUILayout.EndHorizontal();
                GUILayout.EndArea();

                break;

            case 6:

                GUILayout.BeginArea(new Rect(0, 210, 300, 100));
                GUILayout.BeginHorizontal();
                spriteModeInt = EditorGUILayout.IntPopup("Sprite Mode(Sprite 模式)", spriteModeInt, spriteModeString, intArray);
                GUILayout.EndHorizontal();
                GUILayout.EndArea();

                GUILayout.BeginArea(new Rect(0, 240, 300, 100));
                GUILayout.BeginHorizontal();
                GUILayout.Label("Sprite 標籤");
                packingTag = EditorGUILayout.TextArea(packingTag);
                GUILayout.EndHorizontal();
                GUILayout.EndArea();

                GUILayout.BeginArea(new Rect(0, 270, 300, 100));
                GUILayout.BeginHorizontal();
                GUILayout.Label("Pixels Per Unit(每單位像素)");
                pixelsPerUnit = EditorGUILayout.Slider((float)pixelsPerUnit, 0, 100);
                GUILayout.EndHorizontal();
                GUILayout.EndArea();

                break;
        }
    }

    TextureImporter getTextureSettings(string path) {

        TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
        textureImporter.anisoLevel = anisoLevel;

        // textureType (貼圖類型)
        switch (textrueTypeInt){

            case 0:
                textureImporter.textureType = TextureImporterType.Image;
                break;
            case 1:
                textureImporter.textureType = TextureImporterType.Bump;
                break;
            case 2:
                textureImporter.textureType = TextureImporterType.GUI;
                break;
            case 3:
                textureImporter.textureType = TextureImporterType.Reflection;
                break;
            case 4:
                textureImporter.textureType = TextureImporterType.Cookie;
                break;
            case 5:
                textureImporter.textureType = TextureImporterType.Lightmap;
                break;
            case 6:
                textureImporter.textureType = TextureImporterType.Sprite;
                break;
            case 7:
                textureImporter.textureType = TextureImporterType.Advanced;
                break;
                
        }

        // Filter (過濾)
        switch (filterModeInt) {
            case 0:
                textureImporter.filterMode = FilterMode.Point;
                break;
            case 1:
                textureImporter.filterMode = FilterMode.Bilinear;
                break;
            case 2:
                textureImporter.filterMode = FilterMode.Trilinear;
                break;
        }

        // Warp (換行)
        switch (wrapModeInt) {
            case 0:
                textureImporter.wrapMode = TextureWrapMode.Repeat;
                break;
            case 1:
                textureImporter.wrapMode = TextureWrapMode.Clamp;
                break;
        }

        // Max (紋理最大的大小)
        switch (maxSizeInt) {
            case 0:
                textureImporter.maxTextureSize = 32;
                break;
            case 1:
                textureImporter.maxTextureSize = 64;
                break;
            case 2:
                textureImporter.maxTextureSize = 128;
                break;
            case 3:
                textureImporter.maxTextureSize = 256;
                break;
            case 4:
                textureImporter.maxTextureSize = 512;
                break;
            case 5:
                textureImporter.maxTextureSize = 1024;
                break;
            case 6:
                textureImporter.maxTextureSize = 2048;
                break;
            case 7:
                textureImporter.maxTextureSize = 4096;
                break;
        }

        // Format (格式)
        switch (formatInt) {
            case 0:
                textureImporter.textureFormat = TextureImporterFormat.AutomaticCompressed;
                break;
            case 1:
                textureImporter.textureFormat = TextureImporterFormat.Automatic16bit;
                break;
            case 2:
                textureImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor;
                break;
        }

        // TextureType Setting
        switch (textrueTypeInt) {
            case 0:
                textureImporter.alphaIsTransparency = alphaIsTransparen;
                textureImporter.grayscaleToAlpha = alphaFromGraycal;
                break;
            case 4:
                textureImporter.grayscaleToAlpha = alphaFromGraycal;
                break;
            case 6:

                if (spriteModeInt.Equals(0))
                    textureImporter.spriteImportMode = SpriteImportMode.Single;
                else if (spriteModeInt.Equals(1))
                    textureImporter.spriteImportMode = SpriteImportMode.Multiple;

                textureImporter.spritePackingTag = packingTag;
                textureImporter.spritePixelsPerUnit = pixelsPerUnit;

                break;
        }

        return textureImporter;
    }

    /// <summary>
    /// 設置選擇貼圖
    /// </summary>
    void loopSetTexture() {

        Object[] textures = getSelectedTextures();
        Selection.objects = new Object[0];

        foreach (Texture2D texture in textures) {
            string path = AssetDatabase.GetAssetPath(texture);
            TextureImporter texImporter = getTextureSettings(path);
            TextureImporterSettings tis = new TextureImporterSettings();
            texImporter.ReadTextureSettings(tis);
            texImporter.SetTextureSettings(tis);
            AssetDatabase.ImportAsset(path);
        }
    }

    /// <summary>
    /// 選取貼圖
    /// </summary>
    /// <returns></returns>
    Object[] getSelectedTextures() {
        return Selection.GetFiltered(typeof(Texture2D), SelectionMode.DeepAssets);
    }

}

---------------------

結果圖:



2016年9月1日 星期四

Unity EditorGUILayout 製作圖片匯入實例



Script(C#):

using UnityEngine;
using System.Collections;
using UnityEditor;

public class Material : EditorWindow{

    GUIStyle style = new GUIStyle();
    SystemWindowsForm windowsForm = new SystemWindowsForm();
    Vector2 scrollPositionBackGround;

    [MenuItem("遊戲控制器視窗/2D/素材")]
    static void materialWindowFunction() {
        Material materialWindow = new Material();
        materialWindow = (Material)EditorWindow.GetWindow(typeof(Material));
        materialWindow.Show();
    }

    void OnGUI() {
        
        // GUI 風格
        style.fontSize = 18;
        style.normal.textColor = Color.white;

        // GUILayout 自訂位置
        GUILayout.BeginArea(new Rect(0, 0, 170, 30));
        GUILayout.Label("圖片", style);
        GUILayout.EndArea();

        GUILayout.BeginArea(new Rect(0, 30, 170, 30));
        GUILayout.Label("圖片路徑位置:", style);
        GUILayout.EndArea();

        // 背景圖片的路徑名稱
        GUILayout.BeginArea(new Rect(0, 60, 200, 60));
        scrollPositionBackGround = GUILayout.BeginScrollView(scrollPositionBackGround, GUILayout.Width(200),GUILayout.Height(60));
        GUILayout.Box(windowsForm.pathTpye, style);
        GUILayout.EndScrollView();
        GUILayout.EndArea();

        // 背景圖片讀取事件
        EditorGUILayout.BeginHorizontal();
        if (GUI.Button(new Rect(0, 130, 170, 30), GUIContent.none))
            windowsForm.openFile();
        
        GUILayout.BeginArea(new Rect(0, 130, 170, 30));
        GUILayout.Label("背景圖片匯入", style);
        GUILayout.EndArea();
        EditorGUILayout.EndHorizontal();

        // 背景圖片匯入事件
        EditorGUILayout.BeginHorizontal();
        if (GUI.Button(new Rect(180, 130, 50, 30), GUIContent.none))
        {
            if (windowsForm.pathTpye.Equals("No Image"))
                windowsForm.messag("讀不到路徑");
            else {
                windowsForm.CodyImage();
            }
        }
            
        GUILayout.BeginArea(new Rect(180, 130, 50, 30));
        GUILayout.Label("確定", style);
        GUILayout.EndArea();
        EditorGUILayout.EndHorizontal();
    }
}

-------------------------

Script (C#):

using System.Collections;
using System.Windows.Forms;
using System.IO;
using System.Drawing;
using UnityEngine;

public class SystemWindowsForm{

    OpenFileDialog openFileDialog = new OpenFileDialog();

    // 檔案路徑
    private string path = "No Image";
    public string pathTpye {
        get { return path; }
    }

    private string fileName;

    /// <summary>
    /// messageBox 訊息列
    /// </summary>
    /// <param string="訊息"></param>
    public void messag(string message) {
        MessageBox.Show(message);
    }

    /// <summary>
    /// 開啟檔案
    /// </summary>
    public void openFile() {

        openFileDialog.Title = "開啟檔案";
        openFileDialog.Filter = "PNG Image|*.png|JPG Image|*.jpg";
        openFileDialog.ShowDialog();

        switch (openFileDialog.FilterIndex) {
            case 1:
                if (File.Exists(openFileDialog.FileName))
                    path = openFileDialog.FileName;
                    fileName = openFileDialog.SafeFileName;
                break;

            case 2:
                if (File.Exists(openFileDialog.FileName))
                    path = openFileDialog.FileName;
                    fileName = openFileDialog.SafeFileName;
                break;
                
        }
    }

    public void CodyImage() {

        string localPaht = UnityEngine.Application.dataPath + "/GameController/Textrue2D/Background/";
        Bitmap image = new Bitmap(path);

        // 翻轉
        image.RotateFlip(RotateFlipType.Rotate180FlipX); 

        Texture2D readImage = new Texture2D(image.Width, image.Height);

        for (int x = 0; x < image.Width; x++) {
            for (int y = 0; y < image.Height; y++) {
                readImage.SetPixel(x, y, new Color32(image.GetPixel(x, y).R,
                    image.GetPixel(x,y).G,
                    image.GetPixel(x,y).B,
                    image.GetPixel(x,y).A));
            }
        }

        readImage.Apply();
        byte[] imageDate = readImage.EncodeToPNG();
        File.WriteAllBytes(localPaht + fileName, imageDate);

        messag("匯入完成");
    }
}

------------------

結果圖: