webGL平臺Unity打開Color窗口

   

    前一段時間寫過一個windows平臺下unity程序打開顏色窗口的方法,最後需要給出一個在線的小demo展示,當時的顏色窗口是window平臺使用的。所以需要調用html提供的顏色選擇窗口。

    要解決這樣一個問題,首先要實現的是如何在Html上打開一個顏色選擇窗口,並想辦法用unity3d來調用這樣一個方法,這樣就實現了一半。然後利用html獲取到選中的顏色並傳回unity,加載到背景上,就實現了一個點擊ui打開顏色選擇框並加載顏色這樣一個過程。

    1、打開顏色對話窗口

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>html5 input color標籤</title>
	</head>
	<body>
		<input style="display:none;" type="color" id="color" />
		<button id="btn">彈出色盤</button>
	</body>

    <script type='text/javascript'>

document.getElementById('btn').onclick = function(){
	document.getElementById('color').click();
};
document.getElementById('color').onchange = function(){
	alert('您選擇的顏色是:'+this.value)
};
</script>
 </html>

    利用以上代碼在就可以實現一個基本的,打開顏色窗口,顯示所選擇的顏色。

    2、查看Unity調用js,html訪問unity的方法

在unity 的Plugins中新建立一個jslib後綴的文件,並寫入如下代碼:

var WindowDll = {
    OpenColorDialog: function()
    {
        document.getElementById('color').click();
    }
};

mergeInto(LibraryManager.library, WindowDll);

這樣,就可以在C#中導入:


public static class WindowDll
{
    [DllImport("__Internal")]
    public static extern void OpenColorDialog();
}

只需要在其他任何腳本中調用這個OpenColorDialog方法,就可以調用到對應的js文件中的代碼。

    3、修改index.html文檔

在打包生成index.html文件中的body標籤內部,寫入:

<input style="display:none;" type="color" id="color" />

並在任何script標籤內寫入:

 document.getElementById('color').onchange = function(){
    SendMessage("Script","SetColor",this.value);
    }

就可以實現將選中後的顏色傳回到unity的c#方法中,得以實現全過程


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章