2017年11月4日 星期六

UI 簡單的跑馬燈

看到電影有一個字一個字在UI顯示,自己做了一個簡單的程式來玩玩 :)
------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Text;

public class Layout_UI : MonoBehaviour {

    public bool marquee_start; // 跑馬燈開關
    private float marquee_startTime = 0;  // 跑馬燈時間
    public Text text;
 
 // Update is called once per frame
 void Update () {
         
         if (Input.GetKeyDown(KeyCode.W))
            sw = !sw;
       marquee_start = sw;
       
       text.text = system_message_text_Marquee("跑馬燈", 0.4f);
    }

    // 跑馬燈
    private string system_message_text_Marquee(string message, float speed)
    {
        return message.Substring(0, (int)timeData(message.Length, speed));
    }


    // 計數器(跑馬燈用)
    private float timeData(float textSize, float speed)
    {
        float time = (marquee_startTime < textSize && marquee_start.Equals(true)) ? marquee_startTime += speed :
            (marquee_start.Equals(false)) ? marquee_startTime = 0 : marquee_startTime = textSize;
        return time;
    }

}

2017年10月14日 星期六

2017年9月8日 星期五

C# 簡單分割字元及利用正規表達式找到訊息

正規表達式操考網站
正規表達式_測試網站

-----------------------
using System.Collections.Generic;
using System.Text.RegularExpressions;

/// 
/// 括號字元分割
/// 
public class SegmentationSymbol
{
    private string[] specialSymbol = new string[] { "(", ")" };
 
    /// 
    /// 刪除符號字元_括號
    /// 
    /// 
    /// 
    public string delectSymbol(string userMessage)
    {
        string strs = userMessage;

        for (int x = 0; x < specialSymbol.Length; x++)
            strs = strs.Replace(specialSymbol[x], " ");

        return strs;
    }

    /// 
    /// 利用正規表達式
    /// 
    /// 
    public List getA(string message)
    {
        string adjData = @"(\S+ A)";
        List match = new List();

        MatchCollection splitResult = Regex.Matches(message, adjData, RegexOptions.IgnoreCase);
        foreach (Match test in splitResult)
            match.Add(test);

        return match;
    }
}


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


2017年9月1日 星期五

Unity連接MySQL及寫入資料與查詢

請下載 Xmpp 軟體
如果要解決中文上的問題,安裝後請到: D:\xmpp\mysql\bin (本文章是安裝在D曹)
此路徑下找到my.ini檔案下進行更改。
更改內容:
[mysqld]
default-character-set=utf8

[client]
default-character-set=utf8
init_connect='SET NAMES utf8'

再開啟MySql:












開啟後建立自己的資料庫: 本文資料庫名稱 corpus
再建立兩欄資料表 指令:

create table 資料表名稱(
ID integer auto_increment primary key,
Message VARCHAR(20));

若是資料表調整錯誤可以進行網頁頁面更正:












標記框框(解碼中文)




















補充:
自動編號排列指令:
ALTER TABLE test AUTO_INCREMENT = 0

凍仁大大整理的筆記之分享(MySql 指令)~~

Unity(2018版本) 連接 MySQL 套件這裡提供兩個地方載點:
提取码:6rbi

載點2

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

Unity 操作(Script):

using UnityEngine;
using System;
using System.Collections;
using System.Data;
using MySql.Data.MySqlClient;
using System.Text;

public class DataBaseTest : MonoBehaviour
{
    private bool writeDataBaseTable = false;
    private string id = "ID(不必輸入)", message = "請輸入訊息";

    void OnGUI()
    {
        // DataBase 連線按鈕
        GUILayout.BeginArea(new Rect(Screen.width / Screen.width, Screen.height / Screen.height, 200, 30));
        if (GUILayout.Button("Open DataBase InterNet"))
            openDataBase();
        GUILayout.EndArea();

        // DataBase 連線訊息
        GUILayout.BeginArea(new Rect(Screen.width / Screen.width, Screen.height / Screen.height * 30, 200, 30));
        GUILayout.Label(CMySql.result);
        GUILayout.EndArea();

        // 連接DataBase後事件
        if (CMySql.result != "")
        {
            GUILayout.BeginArea(new Rect(Screen.width / Screen.width, Screen.height / Screen.height * 60, 100, 30));
            if(GUILayout.Button("寫入資料")){
                writeDataBaseTable = true;
            }
            GUILayout.EndArea();
        }

        // 寫入資料庫 UI
        if (writeDataBaseTable)
            writeDataUI(); 
    }

    /// 
    /// 寫入資料
    /// 
    void writeDataUI()
    {
        GUILayout.BeginArea(new Rect(Screen.width / Screen.width, Screen.height / Screen.height * 90, 100, 30));
        id = GUILayout.TextField(id, 200);
        GUILayout.EndArea();

        GUILayout.BeginArea(new Rect(Screen.width / Screen.width * 100, Screen.height / Screen.height * 90, 100, 30));
        message = GUILayout.TextField(message, 200);
        GUILayout.EndArea();

        GUILayout.BeginArea(new Rect(Screen.width / Screen.width, Screen.height / Screen.height * 120, 100, 30));
        if (GUILayout.Button("寫入"))
            CMySql.WriteTable( "test" ,id, message);
        GUILayout.EndArea();

        GUILayout.BeginArea(new Rect(Screen.width / Screen.width * 100, Screen.height / Screen.height * 120, 100, 30));
        if (GUILayout.Button("取消"))
            writeDataBaseTable = false;
        GUILayout.EndArea();

    }
    

    /// 
    /// 關閉應用程式
    /// 
    void OnApplicationQuit()
    {
        CMySql.closeSqlConnection();
    }

    /// 
    /// openDataBase
    /// 
    void openDataBase()
    {
        string connectionString = string.Format("Server = {0}; Database = {1}; UserID = {2}; Password = {3};", CMySql.hostType, CMySql.dataBaseType, CMySql.idType, CMySql.passWordTpye);
        CMySql.openSqlConnection(connectionString);
        CMySql.myObjType = CMySql.GetDataSet(connectionString);
        Debug.Log(CMySql.result);
    }
}


資料庫 Script (C#):

/**
 * 2017/8/30 8:10
 * 連接Mysql
 * 寫入資料(中文解決), 讀取資料
 * MySql.Data.MySqlClient download path: https://dev.mysql.com/downloads/connector/net/1.0.html
 * MySql.Data.MySqlClient download path: http://pan.baidu.com/s/1gePtERT 
 */

using System.Collections.Generic;
using System.Data;
using System;
using MySql.Data.MySqlClient;
using System.Text;
using UnityEngine;

public class CMySql
{

    // Just like MyConn.conn in Story Tolls before
    public static MySqlConnection dbConnection;

    // DataBase Ip
    private static string host = "127.0.0.1";
    public static string hostType
    {
        set { host = value; }
        get { return host; }
    }

    // DataBase user Id
    private static string id = "root";
    public static string idType
    {
        set { id = value; }
        get { return id; }
    }

    // DataBase Password
    private static string passWord = "";
    public static string passWordTpye
    {
        set { passWord = value; }
        get { return passWord; }
    }

    // DataBase Name
    private static string dataBase = "corpus";
    public static string dataBaseType
    {
        set { dataBase = value; }
        get { return dataBase; }
    }

    // 連線結果
    public static string result = "";

    // 讀取資 (欄位2)
    static List MessageField2 = new List();

    // DataSet
    private static DataSet myObj;
    public static DataSet myObjType
    {
        set { myObj = value; }
        get { return myObj; }
    }

    // Connect to database
    public static void openSqlConnection(string connectionString)
    {
        dbConnection = new MySqlConnection(connectionString);
        dbConnection.Open();
        result = dbConnection.ServerVersion;
    }

    // closeSql
    public static void closeSqlConnection()
    {
        dbConnection.Close();
        dbConnection = null;
    }

    // MySQL Query
    public static void doQuery(string sqlQuery)
    {
        IDbCommand dbCommand = dbConnection.CreateCommand();
        dbCommand.CommandText = sqlQuery;
        IDataReader reader = dbCommand.ExecuteReader();
        reader.Close();
        reader = null;
        dbCommand.Dispose();
        dbCommand = null;
    }

    #region Get DataSet
    public static DataSet GetDataSet(string sqlString)
    {
        DataSet ds = new DataSet();

        try
        {
            MySqlDataAdapter da = new MySqlDataAdapter(sqlString, dbConnection);
        }
        catch (Exception e)
        {
            throw new Exception("SQL:" + sqlString + "\n");
            e.Message.ToString();
        }
        return ds;
    }
    #endregion

    // 轉utf8
    public static string messageToUtf8(string message)
    {
        UTF8Encoding encoder = new UTF8Encoding();
        byte[] bytes = Encoding.UTF8.GetBytes(message);
        string utf8ReturnString = encoder.GetString(bytes);

        return utf8ReturnString;
    }

    static string ID;
    static string Message;

    // 寫入資料表
    public static void WriteTable(string DataBaseTable ,string id, string message)
    {
        MySqlCommand command = dbConnection.CreateCommand();
       
        string sqlText = "select count(1) from " + DataBaseTable + " where Message=('" + message + "')";

        MySqlCommand cmd1 = new MySqlCommand(sqlText, dbConnection);
        int count = (int)(long)cmd1.ExecuteScalar();
        
        if (count > 0)
        {
            Debug.Log("已經有資料囉");
        }
        else
        {
            ID = id;
            Message = messageToUtf8(message);

            command.CommandText = "Insert into " + DataBaseTable + "(ID, Message) value('" + ID + "','" + Message + "')";
            command.ExecuteNonQuery();

            Debug.Log("載入資料成功");
        }
    }

    /// 
    /// 資料庫查詢
    /// 
    /// 
    /// 
    public static void INQUIRE_TABLE(string dataBaseTitle, string message)
    {
        string sqlText = "select * from " + dataBaseTitle + " where Message='" + message + "'";

        MySqlCommand cmd = new MySqlCommand(sqlText, mySqlConnection);
        MySqlDataReader data = cmd.ExecuteReader();

        while (data.Read())
        {
            try
            {
                UnityEngine.Debug.Log((data[0] + " -- " + data[1]));
            }catch(Exception e)
            {
                data.Close();
                closeSqlConnection();
            }
        }

        data.Close();
    }
}


結果圖:
※寫入資料後,記得Mysql 要重新讀取一次才會出現。










第二筆資輸入:


























若是資料重復:

2017年7月28日 星期五

Unity 基本碰撞範例


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

[RequireComponent(typeof(Rigidbody))]
public class Bullet : MonoBehaviour {

    float speed = 100;

    void Update()
    {
        transform.Translate(Vector3.forward * Time.deltaTime * speed);
        Destroy(gameObject, 3);
    }

    void OnCollisionEnter(Collision collider)
    {
        if (collider.gameObject.name == "物件名稱")
            Debug.Log("aa");
    }
}


2017年7月16日 星期日

更改螢幕大小(解析度)

因由之前製作遊戲過程當中,想要讓玩家調整螢幕之解析度,因此測試了這項的小功能。
意外發現到與Unity本身發佈出來後之解析度有些不同 (目前小弟還在進行研究當中)。

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

public class ScreenResolution : MonoBehaviour
{
    // resolutoion X, Y
    public List resolutionX = new List();
    public List resolutionY = new List();

    public int status;

    void Start()
    {
        resolutionFiltering();
    }

    void OnGUI()
    {
        GUILayout.BeginArea(new Rect(Screen.width / Screen.width, Screen.height / Screen.height, 200, Screen.height));

        if (GUILayout.Button("螢幕解析度切換+"))
            status += 1;

        if (status >= resolutionX.Count && status >= resolutionY.Count)
            status = 0;

        if (GUILayout.Button("確定"))
            Screen.SetResolution(resolutionX[status], resolutionY[status], true);
    

        GUILayout.Label(resolutionX[status].ToString() + " + " + resolutionY[status].ToString());
        GUILayout.Label("目前解析度:" + Screen.width + " + " + Screen.height);
        GUILayout.EndArea();

        Screen.fullScreen = false;  // 不全屏: false  全屏: true
    }

    /// 
    /// 螢幕解析度
    /// 過濾重複的數值
    /// 
    void resolutionFiltering()
    {
        Resolution[] resolutions = Screen.resolutions;

        foreach (Resolution res in resolutions)
        {
            resolutionX.Add(res.width);
            resolutionY.Add(res.height);
        }

        for (int i = resolutionX.Count - 1; i > 0; i--)
        {
            if (resolutionX.IndexOf(resolutionX[i]) != i)
                resolutionX.RemoveAt(i);
        }

        for (int i = resolutionY.Count - 1; i > 0; i--)
        {
            if (resolutionY.IndexOf(resolutionY[i]) != i)
                resolutionY.RemoveAt(i);
        }
    }
}

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




2017年7月9日 星期日

Sprite to Texture2D

Sprite 轉 Texture2D 程式:

    /// 
    /// sprite to Textrue2D
    /// 
    /// 
    /// 
    Texture2D textureFromSprite(Sprite sprite)
    {
        if (sprite.rect.width != sprite.texture.width)
        {
            Texture2D image = new Texture2D(((int)sprite.rect.width), (int)sprite.rect.height);
            Color[] imageColors = sprite.texture.GetPixels((int)sprite.textureRect.x,
                                                           (int)sprite.textureRect.y,
                                                           (int)sprite.textureRect.width,
                                                           (int)sprite.textureRect.height);
            image.SetPixels(imageColors);
            image.Apply();

            return image;
        } else
            return sprite.texture;
    }

2017年5月27日 星期六

Inspector Value List

Script(C#):

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

public class Biochemical_Multitude : ObjectClass
{
    // 物件模式
    public enum SelectObj
    {
        roteObj,
        moveObj,
    }
    public SelectObj objsType;

    // 物件行為方向
    public enum Direction
    {
        forward,
        up,
        down,
        left,
        right,
    }
    public Direction selectDrection;

    public List roteObjs = new List();
    public float roteSpeed;
    public List moveObjs = new List();
    public float moveSpeed;

    void Update()
    {
        switch (objsType)
        {
            case SelectObj.moveObj:
                foreach (Transform tra in moveObjs)
                    Move(tra, driectionFunction(selectDrection), moveSpeed);

                break;

            case SelectObj.roteObj:

                foreach (Transform tra in roteObjs)
                    Rote(tra, driectionFunction(selectDrection), roteSpeed);
                break;
        }
    }

    /// 
    /// 方向
    /// 
    /// 
    /// 
    Vector3 driectionFunction(Direction direction)
    {
        Vector3 vector3 = Vector3.zero;

        switch (direction)
        {
            case Direction.forward:
                vector3 = Vector3.forward;
                break;
            case Direction.up:
                vector3 = Vector3.up;
                break;
            case Direction.down:
                vector3 = Vector3.down;
                break;
            case Direction.left:
                vector3 = Vector3.left;
                break;
            case Direction.right:
                vector3 = Vector3.right;
                break;
        }
        return vector3;
    }
}

----------------------------
Editor Script Script(C#):

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

[CustomEditor(typeof(Biochemical_Multitude))]
public class Biochemical_MultitudeEditor : Editor {
    public override void OnInspectorGUI()
    {
        serializedObject.Update();
        var script = target as Biochemical_Multitude;
        SerializedProperty tps = serializedObject.FindProperty("roteObjs");  // 路徑
        EditorGUI.BeginChangeCheck();
        EditorGUILayout.PropertyField(tps, new GUIContent("roteObjs"), true);
        if (EditorGUI.EndChangeCheck())
            serializedObject.ApplyModifiedProperties();
     }
}

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


2017年4月29日 星期六

隱藏 Inspector 腳本數值

-------物件腳本屬性 C#-------

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

public class Biochemical_Single : ObjectClass {

    // 物件模式
    public enum SelectObj
    {
        roteObj,
        moveObj,
    }
    public SelectObj objsType;

    // 物件行為方向
    public enum Direction
    {
        forward,
        up,
        down,
        left,
        right,
    }
    public Direction direction;

    public Transform tramsform;

    public float moveSpeed, roteSpeed; // 物件行為速度
  
    // Update is called once per frame
    void Update () {

        switch (objsType)
        {
            case SelectObj.moveObj:
                
                    Move(tramsform, driectionFunction(direction), moveSpeed);

                break;

            case SelectObj.roteObj:

                
                    Rote(tramsform, driectionFunction(direction), roteSpeed);
                break;
        }
    }

    /// 
    /// 方向
    /// 
    /// 
    /// 
    Vector3 driectionFunction(Direction direction)
    {
        Vector3 vector3 = Vector3.zero;

        switch (direction)
        {
            case Direction.forward:
                vector3 = Vector3.forward;
                break;
            case Direction.up:
                vector3 = Vector3.up;
                break;
            case Direction.down:
                vector3 = Vector3.down;
                break;
            case Direction.left:
                vector3 = Vector3.left;
                break;
            case Direction.right:
                vector3 = Vector3.right;
                break;
        }
        return vector3;
    }
}

---更改Inspector 腳本GUI顯示(C#)--------


using UnityEngine;
using UnityEditor;
using System;

[CustomEditor(typeof(Biochemical_Single))]  // 更改 Inspector 腳本
public class MyScriptEditor : Editor {

    override public void OnInspectorGUI()
    {
        var script = target as Biochemical_Single;

        script.objsType = (Biochemical_Single.SelectObj)EditorGUILayout.EnumPopup("select Obj", script.objsType);
        script.direction = (Biochemical_Single.Direction)EditorGUILayout.EnumPopup("direction", script.direction);
        script.tramsform = EditorGUILayout.ObjectField(script.tramsform ,typeof(Transform), true) as Transform;

        if (script.objsType == Biochemical_Single.SelectObj.roteObj)
        {
            EditorGUI.indentLevel++;
            EditorGUILayout.PrefixLabel("roteSpeed");
            script.roteSpeed = EditorGUILayout.Slider(script.roteSpeed, script.roteSpeed, 999);
            EditorGUI.indentLevel--;
        }
    }
}
--------執行結果---------
 Select Obj 選擇項目 : Rote Obj














 Select Obj 選擇項目 : Move Obj