UnityVS: Web Target with Web Security enabled will prevent opening files and communication with UnityVS.html
解決方法android
直接在 unity中 File-》build setting -> 更換一個平臺就行,不要選擇web的web
just go to File->Build Settings then select something other than web player and then press Switch Platform. 緩存
======================================================================================
服務器
捕獲日誌多線程
using UnityEngine; using System.Collections; public class SetupVerification : MonoBehaviour { public string message = ""; private bool badSetup = false; void Awake () { Application.RegisterLogCallback (OnLog); } void OnLog (string message, string stacktrace, LogType type) { if (message.IndexOf ("UnityException: Input Axis") == 0 || message.IndexOf ("UnityException: Input Button") == 0 ) { //處理異常信息 } } }
===============================================================app
InternalGetGameObject can only be called from the main thread.dom
而後socketclient對象是異步的,因此作了多線程處理,當socketclient接收到消息時,回調了主線程的函數(繼承自monobehaviour),這時候就致使了報錯。上面第一篇unity論壇博文解釋得比較清楚,大概就是unity對於API調用主線程作了限制:異步
「Unity chose to limit API calls to main-thread, to make a simple and solid threading model that everyone can understand and use.」socket
UIScrollView的更新
void updateScroll(){ //總的高度 float allHeight = uiGrid.transform.childCount * uiGrid.cellHeight; if (allHeight > uiScrollView.gameObject.GetComponent<UIPanel> ().height) { //菜單高度 float btnHeight = buttonClickSingerClass.gameObject.GetComponent<BoxCollider> ().size.y; btnHeight = btnHeight * buttonGrid.transform.childCount; float offset = uiGrid.cellHeight * 0.66f; float curHeight = Mathf.Abs (gameObject.transform.localPosition.y) + btnHeight + offset; if (curHeight > allHeight) { uiScrollView.verticalScrollBar.value = 1.0f; } uiScrollView.UpdatePosition (); } }
旋轉
using UnityEngine; public class DragRotate : MonoBehaviour { public GameObject obj; void Start() { } void OnDrag(Vector2 v){ if (obj != null){ obj.transform.localEulerAngles -= Vector3.up * v.x; } } }
轉化爲00:00:00
static string timeCv(int value){ string str = ""; if (value >= 0) { if (value < 10) str = "0" + value; else str = value.ToString(); } else { str = "00"; } return str; } static string TimeFormat(int s){ int hour = s / 3600; int mm = 0; int ss = 0; if (hour > 0) { mm = (s % 3600)/60; ss = s - hour * 3600 - mm * 60; } else { mm = s / 60; ss = s - hour * 3600 - mm * 60; } return timeCv (hour) + ":" + timeCv (mm) + ":" + timeCv (ss); }
ReadPixels 須要等待一幀後才能處理.
ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame.
StartCoroutine(screenAndUpload()); IEnumerator screenAndUpload(){ Texture2D tex = new Texture2D(Screen.width,Screen.height); //ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame. //這個須要你在調用這個函數以前使用yield return new WaitForEndOfFrame();
yield return new WaitForEndOfFrame(); tex.ReadPixels(new Rect(0,0,Screen.width,Screen.height),0,0); tex.Apply(); byte[] bytes = tex.EncodeToPNG(); Destroy(tex); WWWForm form = new WWWForm (); form.AddField ("frameCount",Time.frameCount.ToString()); form.AddBinaryData ("fileUpload", bytes, "screenShot.png", "image/png"); WWW w = new WWW ("http://127.0.0.1/cgi-bin/savelog.cgi", form); StartCoroutine (screenAndUploadCoroutine(w)); } IEnumerator screenAndUploadCoroutine(WWW w){ yield return w; if (!String.IsNullOrEmpty (w.error)){ print (w.error); }else{ print ("Finished Uploading ScreenShot!"); } }
unity3d post 二進制數據流到web 服務器
IEnumerator screenAndUpload(){ WWWForm form = new WWWForm (); form.AddField ("frameCount","("+Time.frameCount.ToString()+")"); byte[] _uploadBytes = testBytes; form.AddBinaryData ("bytes", testBytes,"");//_uploadBytes.Length.ToString() WWW w = new WWW ("http://127.0.0.1/cgi-bin/savelog.cgi", form); StartCoroutine (screenAndUploadCoroutine(w)); } byte[] testBytes{ get{ byte[] bytes = new byte[] {65,66,97,98}; return bytes; } } IEnumerator screenAndUploadCoroutine(WWW w){ yield return w; if (!String.IsNullOrEmpty (w.error)){ //print (w.error); }else{ //print ("Finished Uploading ScreenShot!"); print(w.data); } }
--zcYvw8EWu622BRvwDuR9ZMyucYxHAapZXRlzb4Sa
Content-Type: text/plain; charset="utf-8"
Content-disposition: form-data; name="frameCount"
(756)
--zcYvw8EWu622BRvwDuR9ZMyucYxHAapZXRlzb4Sa
Content-Type: application/octet-stream
Content-disposition: form-data; name="bytes"; filename=""
ABab
--zcYvw8EWu622BRvwDuR9ZMyucYxHAapZXRlzb4Sa--
������������
UnityEngine.MonoBehaviour:print(Object)
<screenAndUploadCoroutine>c__Iterator4:MoveNext() (at Assets/Script/Login.cs:81)
saveCgi.c
#include <stdio.h> #include <stdlib.h> void main(int argc, char *argv[]){ int i, n; //fprintf( stdout, "Content-type:application/octet-stream\n\n" ); //fprintf( stdout, "<html><title>post</title>" ); if( getenv("CONTENT_LENGTH") ){ n = atoi( getenv("CONTENT_LENGTH") ); }else { n = 0; fprintf( stdout, "(NULL)" ); } for( i=0; i<n; i++ ){ fputc( getc(stdin), stdout ); } fprintf( stdout, "" ); }
print Logs message to the Unity Console (identical to Debug.Log).
在控制檯輸出日誌,等同於Debug.Log
TweenAlpha 使用
using UnityEngine; using System.Collections; public class Init :MonoBehaviour { public Transform cube; public GameObject alphaGo; public UIWidget button; void Awake() { //print(gameObject.name); } void Update(){ if(cube!=null) cube.transform.Rotate(new Vector3(0.1f,0.1f,0.1f)); } void Start(){ UIEventListener.Get(button.gameObject).onClick = onClickHandle; } void onClickHandle(GameObject go){ if(alphaGo!=null){ alphaGo.GetComponent<UIWidget>().alpha = 0.0f; StopCoroutine("delScript"); TweenAlpha.Begin(alphaGo,5.0f,1.0f); StartCoroutine("delScript",alphaGo); } } IEnumerator delScript(GameObject go){ yield return new WaitForSeconds(5.0f); TweenAlpha ta = go.GetComponent<TweenAlpha>(); if(ta!=null) Destroy(ta); } }
TweenPosition使用
using UnityEngine; public class TweenPostionExample :MonoBehaviour { public UIWidget btn; public GameObject tweenObj; void Start(){ tweenObj.transform.localPosition = Vector3.zero; UIEventListener.Get(btn.gameObject).onClick = onClickHandle; } void onClickHandle(GameObject go){ Debug.Log(go.name); ResetExecute(); EventDelegate eventDelegate = new EventDelegate(this,"onTpFinish"); TweenPosition tp = TweenPosition.Begin(tweenObj,0.2f,new Vector3(200,-100,0)); tp.onFinished.Clear(); tp.onFinished.Add(eventDelegate); } void onTpFinish(){ Debug.Log("end.."); } [ContextMenu("ResetExecute")] public void ResetExecute (){ tweenObj.transform.localPosition = Vector3.zero; } }
如何動態的給EventDelegate添加參數
using UnityEngine; using System.Collections; public class SZEventDelegateParams : MonoBehaviour { public int param = 2; void Start(){ // 建立新的delegate,最後調用此(this)腳本的Finished函數。固然this能夠換成別的腳本,這裏爲了方便 EventDelegate eventDelegate = new EventDelegate(this, "Finished"); // 把第一個參數設置爲此(this)腳本的param變量。<span style="font-family: Arial; ">固然this能夠換成別的腳本,這裏爲了方便</span> eventDelegate.parameters[0] = new EventDelegate.Parameter(this, "param"); UIPlayTween uipt = this.GetComponent<UIPlayTween>(); uipt.onFinished.Add(eventDelegate); uipt.Play(true); } // PlayTween 結束後,會調用到這裏,打印相應的值 void Finished(int p){ Debug.Log(p.ToString()); } }
隨機數(防止ie緩存)
string url = "http://127.0.0.1/cgi-bin/savelog.cgi" + "?" + UnityEngine.Random.Range (0.0f, 1.0f); http://127.0.0.1/cgi-bin/savelog.cgi?0.4753303
MonoDevelop幾個經常使用的快捷鍵
Tools/Options/Key bindings
CTRL+K 刪除光標所在行的該行後面的代碼
CTRL + ALT +C 註釋/不註釋該行
CTRL+ DOWN 像鼠標滾輪同樣向下拖
CTRL + UP 像鼠標滾輪同樣向上拖
CTRL + F 查找該腳本
CTRL + SHIFT + F 查找所有腳本
CTRL + H 替換代碼
CTRL + SHIFT +W 關掉全部腳本
CTRL + G 跳轉到指定的行
C#回調
public delegate void Callback();
加載texture
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class AssetBunder :MonoBehaviour { void Start () { WWW www = new WWW("http://192.168.1.10/AssetBundle/PC/role_1001hs.unity3d"); StartCoroutine (downLoad(www)); } IEnumerator downLoad (WWW w) { yield return w; UnityEngine.Object obj = w.assetBundle.mainAsset; Texture2D tex = obj as Texture2D; UITexture texture = GetComponent<UITexture>(); texture.mainTexture = tex; yield return new WaitForSeconds(3.0f); DestroyImmediate(texture); } }
C#List排序
class ComparerDynamicByTime:IComparer<MeetDynamicItemVO>{ public int Compare(MeetDynamicItemVO x,MeetDynamicItemVO y){ if (x.time < y.time) { return 1; } return -1; } } List<MeetDynamicItemVO> _dynList = new List<MeetDynamicItemVO> (); _dynList.Sort (new ComparerDynamicByTime ());
UIDrag Object
/// Allows dragging of the specified target object by mouse or touch, optionally limiting it to be within the UIPanel's clipped rectangle.
使用鼠標或者是觸碰來拖拽UIPanel剪切矩形區域範圍內的窗口
HudText飄血特效實現
using UnityEngine; using System.Collections; public class HUDTextTest :MonoBehaviour { public HUDText hudText; void Start () { //hudText.Add("hello",Color.red,0.0f); UIEventListener.Get (gameObject).onClick = onClickHandle; } void onClickHandle (GameObject go) { if (hudText != null) { hudText.Add (UnityEngine.Random.Range (0.0f, 1.0f).ToString (), Color.red, 0.0f); } StartCoroutine (EnableDragScrollView ()); } protected IEnumerator EnableDragScrollView () { yield return new WaitForSeconds (1.0f); GameObject obj = GameObject.Find ("GameObject"); while (obj!=null && obj.transform.childCount > 0) { DestroyImmediate (obj.transform.GetChild (0).gameObject); } } void Update () { } }
射線拾取模型
void Update() { if (rootCreat.activeSelf && creatState == false && Input.GetMouseButtonDown(0)) { if (!UICamera.Raycast(Input.mousePosition))//沒有碰到NGUI { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//從攝像機發出到點擊座標的射線 RaycastHit hitInfo; if (Physics.Raycast(ray, out hitInfo)) { GameObject gameObj = hitInfo.collider.gameObject; int num = 0; if (int.TryParse(gameObj.name, out num)) { ButtonCreatChoose(gameObj.name); } } } } }
Camera.main = null的問題 設置一個Camera的tar= MainCamera
設置RenderQ,設置材質渲染隊列,改變先後層關係,RenderQ越大 就越在前面,就越先看到
using UnityEngine; using System.Collections; [AddComponentMenu("Tool/Change RenderQueue")] public class ChangeRenderQueue : MonoBehaviour { public int queue = 0; void Awake() { renderer.material.renderQueue = queue; Destroy(this); } }
翻牌
using UnityEngine; using System.Collections; public class TweenFlipCARDS : MonoBehaviour { public GameObject positive; /// 牌正面 public GameObject reverse; /// 牌背面 public float durationTime = 0.5f; /// 半圈時間 [HideInInspector] public EventDelegate.Callback endCallBack; void Start () { reset(); } [ContextMenu("Play")] public void play() { StartCoroutine(IPlay()); } IEnumerator IPlay(){ yield return new WaitForEndOfFrame(); positive.SetActive(true); reverse.SetActive(false); TweenRotation mPositiveTween = TweenRotation.Begin(positive,durationTime,Quaternion.Euler(Vector3.zero)); mPositiveTween.from = Vector3.zero; mPositiveTween.to = new Vector3 (0, 90, 0); EventDelegate.Add (mPositiveTween.onFinished, positiveEnd); mPositiveTween.Play(); } [ContextMenu("Reset")] public void reset() { positive.SetActive(true); reverse.SetActive(false); positive.transform.localRotation = Quaternion.Euler(Vector3.zero); reverse.transform.localRotation = Quaternion.Euler(new Vector3(0,90,0)); } void positiveEnd () { positive.SetActive(false); reverse.SetActive(true); TweenRotation mReverseTween = TweenRotation.Begin(reverse,durationTime,Quaternion.Euler(Vector3.zero)); mReverseTween.enabled = true; mReverseTween.from = new Vector3 (0, -90, 0); mReverseTween.to = Vector3.zero; EventDelegate.Add (mReverseTween.onFinished, reverseEnd); mReverseTween.Play(); } void reverseEnd() { // Debug.Log("ReverseEnd..."); if(endCallBack != null) endCallBack(); } }
抖屏
iTween.ShakePosition(GameObject.Find("Camera").gameObject,new Vector3(0.1f,0.1f,0.1f),1.0f);
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Card : MonoBehaviour { public static Card instance; const float useTime = 0.5f; void Start() { } List<GameObject> list = new List<GameObject>(); void Awake() { instance =this; GameObject child = gameObject.transform.GetChild(0).gameObject; for(int i = 0;i < child.transform.childCount;i++) { list.Add(child.transform.GetChild(i).gameObject); } // Debug.Log(list.Count); } public void onHover(GameObject go) { int index = int.Parse(go.name.Substring(go.name.Length - 1,1)); GameObject cur = list[index]; TweenRotation tr = TweenRotation.Begin(go,useTime,Quaternion.Euler(Vector3.zero)); tr.Play(); for(int i = 0;i < list.Count;i++){ if(i < index) { rotateTarget(list[i],true); } else if(i > index) { rotateTarget(list[i],false); } } } void rotateTarget(GameObject go,bool isReverse) { // Debug.Log("rotate:" + go.name); TweenRotation tr = TweenRotation.Begin(go,useTime,Quaternion.Euler(new Vector3())); tr.to = new Vector3(0,(isReverse == true ? 45 : 135),0); tr.Play(); } } /* using UnityEngine; using System.Collections; using System.Collections.Generic; public class CardItem :MonoBehaviour { public CardItem () { } void Start () { UIEventListener.Get (gameObject).onClick = onClickHandle; UIEventListener.Get (gameObject).onHover = onHoverHandle; } void onClickHandle (GameObject go) { } void onHoverHandle (GameObject go, bool state) { if (state) { TweenRotation.Begin (go, 0.5f, Quaternion.Euler (new Vector3 (0, 45, 0))); Card.instance.onHover(go); } // Debug.Log (go.name + "," + state.ToString ()); } } */
==========================================
Resources:此文件夾內的文件可使用Rescources.Load加載,thus all assets in the "Resources" folders will be included in a build.全部在Resources文件下的資源將被編譯在一塊兒,在android編譯的時候 會壓縮成一個zip文件.若是資源不須要了使用 Resources.UnloadUnusedAssets.釋放內存
==========================================
Building Setting 中添加關卡:
Application.LoadLevel(sn);(同步加載會刪除掉當前場景),異步測試會附加關卡數據
==========================================
unity3d中類static常駐,即便是loadLevel切換關卡的時候.這樣腳本即便卸載了,那麼static存儲的數據還在.
using UnityEngine; using System.Collections; public class Test :MonoBehaviour { public static int count = 0; [HideInInspector] public int tempCount = 0; public GameObject btn; void Start() { count++; tempCount++; Debug.Log("count: "+count + " tempCount: " + tempCount);//count會自增變化,tempCount不會自增變化 if(btn!=null) { UIEventListener.Get(btn).onClick = onClickHandle; } } void onClickHandle(GameObject obj) { StartCoroutine(SceneFadeOut()); } IEnumerator SceneFadeOut() { yield return new WaitForEndOfFrame(); if(Application.loadedLevelName == "Test") { Application.LoadLevel("load"); } else { Application.LoadLevel("Test"); } } }
關於unity3d中單例的問題,基類中綁定到一個全局GameObject上
using UnityEngine; using System.Collections; using System.Collections.Generic; public class ManagerBase<T> : EventDispatcher where T : MonoBehaviour { private static T _instance; public static T instance { get { if(_instance == null && GameControl.instance != null) { _instance = GameControl.instance.gameObject.AddComponent<T>(); GameControl.managerList.Add(_instance as ManagerInterface); } return _instance; } } void OnDestroy() { _instance = null; } }
OnDestroy()的使用
在對象銷燬滅的時候調用,銷魂場景裏的數據.
void OnDestroy() { MeetManager.instance.RemoveEvent(MeetManager.EVENT_CREATE_MEET); }
UITable:表格佈局管理器
播放一個fbx動畫
using UnityEngine; public class Test : MonoBehaviour { [ContextMenu("Play")] public void Play() { Animator anim = gameObject.GetComponent<Animator>(); if (anim!=null) { anim.Play("attack"); } else { Debug.Log("there is no anim!"); } } }
war3 下拉菜單動畫
/* war3下拉菜單動畫 */ IEnumerator StartPlay() { GameObject go = BottomWindow.gameObject; go.transform.localPosition = new Vector3(21, 134f, 0.0f); TweenPosition tp = TweenPosition.Begin(go, 0.5f, new Vector3()); tp.from = new Vector3(21, 134f, 0.0f); tp.to = new Vector3(21, -235f, 0.0f); tp.Play(); yield return new WaitForSeconds(0.5f); tp = TweenPosition.Begin(go, 0.3f, new Vector3()); tp.from = new Vector3(21, -235f, 0.0f); tp.to = new Vector3(21, -175f, 0.0f); tp.Play(); yield return new WaitForSeconds(0.3f); tp = TweenPosition.Begin(go, 0.3f, new Vector3()); tp.from = new Vector3(21, -175f, 0.0f); tp.to = new Vector3(21, -202f, 0.0f); tp.Play(); yield return new WaitForSeconds(0.3f); PlayEnd(); }
/* * 傳入毫秒,返回偏差值 * 返回值 > 0 則服務器時間比本地時間快 * 返回值 < 0 則服務器時間比本地時間慢 */ static void TimeSub(long ms) { DateTime d = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(ms).ToLocalTime(); DateTime nowdatetime = DateTime.Now; DateTime enddatetime = Convert.ToDateTime(d); TimeSpan nowtimespan = new TimeSpan(nowdatetime.Ticks); TimeSpan endtimespan = new TimeSpan(enddatetime.Ticks); TimeSpan timespan = nowtimespan.Subtract(endtimespan).Duration(); //TimeCountLbl.Text = "距離" + textBox1.Text + "還有" + timespan.TotalSeconds.ToString() + "秒"; Console.WriteLine(">>"+timespan.TotalSeconds + " s"); }
================================================
cmd命裏行編譯輸出web
/** /Applications/Unity/Unity.app/Contents/MacOS/Unity \ -batchmode \ -quit \ -projectPath $PROJECT_PATH \ -executeMethod CommandBuild.BuildAndroid */ // Assets/Editor/CommandBuile.cs using UnityEngine; using UnityEditor; public class BuildWeb { public static void build() { string[] levels = {"Assets/Scence/Test.unity"}; BuildPipeline.BuildPlayer(levels, "SampleWeb", BuildTarget.WebPlayer, BuildOptions.None); } } //批處理 //文件生成在項目根目錄下 //"C:\Program Files (x86)\Unity\Editor\Unity.exe" -quit -batchmode -executeMethod BuildWeb.build //pause
Cmd 輸出Android
/** /Applications/Unity/Unity.app/Contents/MacOS/Unity \ -batchmode \ -quit \ -projectPath $PROJECT_PATH \ -executeMethod CommandBuild.BuildAndroid */ // Assets/Editor/CommandBuile.cs using UnityEngine; using UnityEditor; public class CommandBuild { public static void BuildAndroid() { string[] levels = {"Assets/Scence/S0.unity"}; BuildPipeline.BuildPlayer(levels, "Sample.apk", BuildTarget.Android, BuildOptions.None); } } //批處理 //"C:\Program Files (x86)\Unity\Editor\Unity.exe" -quit -batchmode -executeMethod CommandBuild.BuildAndroid //文件生成在項目根目錄下
CMD輸出時間格式
@echo off call:systime "C:\Program Files (x86)\Unity\Editor\Unity.exe" -quit -batchmode -executeMethod BuildWeb.build call:systime echo.&goto:eof ::-------------------------------------------------------- ::-- 函數部分開始::--------------------------------------- :systime ::獲取日期 將格式設置爲:20110820 set datevar=%date:~0,4%.%date:~5,2%.%date:~8,2% ::獲取時間中的小時 將格式設置爲:24小時制 set timevar=%time:~0,2% if /i %timevar% LSS 10 ( set timevar=0%time:~1,1% ) ::獲取時間中的分、秒 將格式設置爲:3220 ,表示 32分20秒 set timevar=%timevar%:%time:~3,2%:%time:~6,2% @echo %datevar%-%timevar% goto:eof ::測試函數 :printf echo .this is CMD function! goto:eof
添加一個unity3D運行的環境變量:
個人電腦/屬性/高級/環境變量-->系統變量-->編輯系統變量 Path (D:\software\unity3D\Editor)bat 中的(Unity.exe -quit -batchmode -executeMethod BuildWindowExe.build)