请问有人遇到过CameraPath3命令编辑器进入路径路径后导入Unity 在pc上运行都能卡死的情况?

用Unity3D制作基于web的网络游戏,不可避免的会用到一个技术-资源动态加载。比如想加载一个大场景的资源,不应该在游戏的开始让用户长时间等待全部资源的加载完毕。应该优先加载用户附近的场景资源,在游戏的过程中,不影响操作的情况下,后台加载剩余的资源,直到所有加载完毕。本文包含一些代码片段讲述实现这个技术的一种方法。本方法不一定是最好的,希望能抛砖引玉。代码是C#写的,用到了Json,还有C#的事件机制。在讲述代码之前,先想象这样一个网络游戏的开发流程。首先美工制作场景资源的3D建模,游戏设计人员把3D建模导进Unity3D,托托拽拽编辑场景,完成后把每个gameobject导出成XXX.unity3d格式的资源文件(参看BuildPipeline),并且把整个场景的信息生成一个配置文件,xml或者Json格式(本文使用Json)。最后还要把资源文件和场景配置文件上传到服务器,最好使用CMS管理。客户端运行游戏时,先读取服务器的场景配置文件,再根据玩家的位置从服务器下载相应的资源文件并加载,然后开始游戏,注意这里并不是下载所有的场景资源。在游戏的过程中,后台继续加载资源直到所有加载完毕。一个简单的场景配置文件的例子:MyDemoSence.txt
&&&&"AssetList" : [{
&&&&&&&&"Name" : "Chair 1",
&&&&&&&&"Source" : "Prefabs/Chair001.unity3d",
&&&&&&&&"Position" : [2,0,-5],
&&&&&&&&"Rotation" : [0.0,60.0,0.0]
&&&&&&&&"Name" : "Chair 2",
&&&&&&&&"Source" : "Prefabs/Chair001.unity3d",
&&&&&&&&"Position" : [1,0,-5],
&&&&&&&&"Rotation" : [0.0,0.0,0.0]
&&&&&&&&"Name" : "Vanity",
&&&&&&&&"Source" : "Prefabs/vanity001.unity3d",
&&&&&&&&"Position" : [0,0,-4],
&&&&&&&&"Rotation" : [0.0,0.0,0.0]
&&&&&&&&"Name" : "Writing Table",
&&&&&&&&"Source" : "Prefabs/writingTable001.unity3d",
&&&&&&&&"Position" : [0,0,-7],
&&&&&&&&"Rotation" : [0.0,0.0,0.0],
&&&&&&&&"AssetList" : [{
&&&&&&&&&&&&"Name" : "Lamp",
&&&&&&&&&&&&"Source" : "Prefabs/lamp001.unity3d",
&&&&&&&&&&&&"Position" : [-0.5,0.7,-7],
&&&&&&&&&&&&"Rotation" : [0.0,0.0,0.0]
&&&&&&&&}]
AssetList:场景中资源的列表,每一个资源都对应一个unity3D的gameobjectName:gameobject的名字,一个场景中不应该重名Source:资源的物理路径及文件名Position:gameobject的坐标Rotation:gameobject的旋转角度你会注意到Writing Table里面包含了Lamp,这两个对象是父子的关系。配置文件应该是由程序生成的,手工也可以修改。另外在游戏上线后,客户端接收到的配置文件应该是加密并压缩过的。主程序:
public class MainMonoBehavior : MonoBehaviour {
&&&&public delegate void MainEventHandler(GameObject dispatcher);
&&&&public event MainEventHandler StartE
&&&&public event MainEventHandler UpdateE
&&&&public void Start() {
&&&&&&&&ResourceManager.getInstance().LoadSence("Scenes/MyDemoSence.txt");
&&&&&&&&if(StartEvent != null){
&&&&&&&&&&&&StartEvent(this.gameObject);
&&&&public void Update() {
&&&&&&&&if (UpdateEvent != null) {
&&&&&&&&&&&&UpdateEvent(this.gameObject);
这里面用到了C#的事件机制,大家可以看看我以前翻译过的国外一个牛人的文章。在start方法里调用ResourceManager,先加载配置文件。每一次调用update方法,MainMonoBehavior会把update事件分发给ResourceManager,因为ResourceManager注册了MainMonoBehavior的update事件。ResourceManager.cs
private MainMonoBehavior mainMonoB
private string mResourceP
private Scene mS
private Asset mSceneA
private ResourceManager() {
&&&&mainMonoBehavior = GameObject.Find("Main Camera").GetComponent&MainMonoBehavior&();
&&&&mResourcePath = PathUtil.getResourcePath();
public void LoadSence(string fileName) {
&&&&mSceneAsset = new Asset();
&&&&mSceneAsset.Type = Asset.TYPE_JSON;
&&&&mSceneAsset.Source = fileN
&&&&mainMonoBehavior.UpdateEvent += OnU
在LoadSence方法里先创建一个Asset的对象,这个对象是对应于配置文件的,设置type是Json,source是传进来的&Scenes/MyDemoSence.txt&。然后注册MainMonoBehavior的update事件。
public void OnUpdate(GameObject dispatcher) {
&&&&if (mSceneAsset != null) {
&&&&&&&&LoadAsset(mSceneAsset);
&&&&&&&&if (!mSceneAsset.isLoadFinished) {
&&&&&&&&&&&&
&&&&&&&&//clear mScene and mSceneAsset for next LoadSence call
&&&&&&&&mScene =
&&&&&&&&mSceneAsset =
&&&&mainMonoBehavior.UpdateEvent -= OnU
OnUpdate方法里调用LoadAsset加载配置文件对象及所有资源对象。每一帧都要判断是否加载结束,如果结束清空mScene和mSceneAsset对象为下一次加载做准备,并且取消update事件的注册。最核心的LoadAsset方法:
private Asset LoadAsset(Asset asset) {
&&&&string fullFileName = mResourcePath + "/" + asset.S
&&&&//if www resource is new, set into www cache
&&&&if (!wwwCacheMap.ContainsKey(fullFileName)) {
&&&&&&&&if (asset.www == null) {
&&&&&&&&&&&&asset.www = new WWW(fullFileName);
&&&&&&&&&&&&
&&&&&&&&if (!asset.www.isDone) {
&&&&&&&&&&&&
&&&&&&&&wwwCacheMap.Add(fullFileName, asset.www);
传进来的是要加载的资源对象,先得到它的物理地址,mResourcePath是个全局变量保存资源服务器的网址,得到fullFileName类似。然后通过wwwCacheMap判断资源是否已经加载完毕,如果加载完毕把加载好的www对象放到Map里缓存起来。看看前面Json配置文件,Chair 1和Chair 2用到了同一个资源Chair001.unity3d,加载Chair 2的时候就不需要下载了。如果当前帧没有加载完毕,返回null等到下一帧再做判断。这就是WWW类的特点,刚开始用WWW下载资源的时候是不能马上使用的,要等待诺干帧下载完成以后才可以使用。可以用yield返回www,这样代码简单,但是C#要求调用yield的方法返回IEnumerator类型,这样限制太多不灵活。继续LoadAsset方法:
&&&&if (asset.Type == Asset.TYPE_JSON) { //Json
&&&&&&&&if (mScene == null) {
&&&&&&&&&&&&string jsonTxt = mSceneAsset.www.
&&&&&&&&&&&&mScene = JsonMapper.ToObject&Scene&(jsonTxt);
&&&&&&&&//load scene
&&&&&&&&foreach (Asset sceneAsset in mScene.AssetList) {
&&&&&&&&&&&&if (sceneAsset.isLoadFinished) {
&&&&&&&&&&&&&&&&
&&&&&&&&&&&&} else {
&&&&&&&&&&&&&&&&LoadAsset(sceneAsset);
&&&&&&&&&&&&&&&&if (!sceneAsset.isLoadFinished) {
&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&}
代码能够运行到这里,说明资源都已经下载完毕了。现在开始加载处理资源了。第一次肯定是先加载配置文件,因为是Json格式,用JsonMapper类把它转换成C#对象,我用的是LitJson开源类库。然后循环递归处理场景中的每一个资源。如果没有完成,返回null,等待下一帧处理。继续LoadAsset方法:
&&&&else if (asset.Type == Asset.TYPE_GAMEOBJECT) { //Gameobject
&&&&&&&&if (asset.gameObject == null) {
&&&&&&&&&&&&wwwCacheMap[fullFileName].assetBundle.LoadAll();
&&&&&&&&&&&&GameObject go = (GameObject)GameObject.Instantiate(wwwCacheMap[fullFileName].assetBundle.mainAsset);
&&&&&&&&&&&&UpdateGameObject(go, asset);
&&&&&&&&&&&&asset.gameObject =
&&&&&&&&if (asset.AssetList != null) {
&&&&&&&&&&&&foreach (Asset assetChild in asset.AssetList) {
&&&&&&&&&&&&&&&&if (assetChild.isLoadFinished) {
&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&} else {
&&&&&&&&&&&&&&&&&&&&Asset assetRet = LoadAsset(assetChild);
&&&&&&&&&&&&&&&&&&&&if (assetRet != null) {
&&&&&&&&&&&&&&&&&&&&&&&&assetRet.gameObject.transform.parent = asset.gameObject.
&&&&&&&&&&&&&&&&&&&&} else {
&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&}
&&&&asset.isLoadFinished =
终于开始处理真正的资源了,从缓存中找到www对象,调用Instantiate方法实例化成Unity3D的gameobject。UpdateGameObject方法设置gameobject各个属性,如位置和旋转角度。然后又是一个循环递归为了加载子对象,处理gameobject的父子关系。注意如果LoadAsset返回null,说明www没有下载完毕,等到下一帧处理。最后设置加载完成标志返回asset对象。UpdateGameObject方法:
private void UpdateGameObject(GameObject go, Asset asset) {
&&&&//name
&&&&go.name = asset.N
&&&&//position
&&&&Vector3 vector3 = new Vector3((float)asset.Position[0], (float)asset.Position[1], (float)asset.Position[2]);
&&&&go.transform.position = vector3;
&&&&//rotation
&&&&vector3 = new Vector3((float)asset.Rotation[0], (float)asset.Rotation[1], (float)asset.Rotation[2]);
&&&&go.transform.eulerAngles = vector3;
这里只设置了gameobject的3个属性,眼力好的同学一定会发现这些对象都是&死的&,因为少了脚本属性,它们不会和玩家交互。设置脚本属性要复杂的多,编译好的脚本随着主程序下载到本地,它们也应该通过配置文件加载,再通过C#的反射创建脚本对象,赋给相应的gameobject。最后是Scene和asset代码:
public class Scene {
&&&&public List&Asset& AssetList {
public class Asset {
&&&&public const byte TYPE_JSON = 1;
&&&&public const byte TYPE_GAMEOBJECT = 2;
&&&&public Asset() {
&&&&&&&&//default type is gameobject for json load
&&&&&&&&Type = TYPE_GAMEOBJECT;
&&&&public byte Type {
&&&&public string Name {
&&&&public string Source {
&&&&public double[] Bounds {
&&&&public double[] Position {
&&&&public double[] Rotation {
&&&&public List&Asset& AssetList {
&&&&public bool isLoadFinished {
&&&&public WWW www {
&&&&public GameObject gameObject {
代码就讲完了,在我实际测试中,会看到gameobject一个个加载并显示在屏幕中,并不会影响到游戏操作。代码还需要进一步完善适合更多的资源类型,如动画资源,文本,字体,图片和声音资源。动态加载资源除了网络游戏必需,对于大公司的游戏开发也是必须的。它可以让游戏策划(负责场景设计),美工和程序3个角色独立出来,极大提高开发效率。试想如果策划改变了什么NPC的位置,美工改变了某个动画,或者改变了某个程序,大家都要重新倒入一遍资源是多么低效和麻烦的一件事。
阅读(...) 评论()【Unity】技巧集合
转发,请保持地址:
相关文章:
这篇文章将收集unity的相关技巧,会不断地更新内容。
1. 保存运行中的状态
unity在运行状态时是不能够保存的。但在运行时编辑的时候,有时会发现比较好的效果想保存。这时可以在 “Hierarchy”中复制相关对象树,暂停游戏后替换原来的,就可以了。(其实这个拷贝过程是序列化过程,这种方法是序列化到内存中;另外一种方法就是序列化到磁盘上,即把内容拖动到文件夹中变成prefab,效果也是一样的)
2. Layer的用法
LayerMask.NameToLayer("Ground");
// 通过名字获取layer
3D Raycast
if(Physics.Raycast(cam3d.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, (1&&LayerMask.NameToLayer("Ground")))) {
2D Raycast
Collider2D h = Physics2D.OverlapPoint(Input.mousePosition, (1&&LayerMask.NameToLayer("xxx")));
uGUI中的做法:
void Update () {
if (Input.GetMouseButtonDown (0)) {
if (EventSystem.current.IsPointerOverGameObject ()) {
PointerEventData pe = new PointerEventData(EventSystem.current);
pe.position =
Input.mouseP
List&RaycastResult& hits = new List&RaycastResult&();
EventSystem.current.RaycastAll( pe, hits );
foreach(RaycastResult h in hits) {
if(h.gameObject.layer == tangramLayer) {
Debug.Log("======" + Time.time + ", obj: " + h.gameObject.name);
..................3. 物理摄像头取色(WebCamTexture)
Texture2D exactCamData() {
// get the sample pixels
Texture2D snap = new Texture2D((int)detectSize.x, (int)detectSize.y);
snap.SetPixels(webcamTexture.GetPixels((int)detectStart.x, (int)detectStart.y, (int)detectSize.x, (int)detectSize.y));
snap.Apply();
保存截图:
System.IO.File.WriteAllBytes(Application.dataPath + "/test.png", exactCamData().EncodeToPNG());
4. 操作componenent
CircleCollider2D cld = (CircleCollider2D)colorYuan[i].AddComponent(typeof(CircleCollider2D));
cld.radius = 1;
Destroy(transform.gameObject.GetComponent&SpriteRenderer&());
5. 动画相关
状态Init到状态fsShake的的条件为:参数shake==true;代码中的写法:
触发fsShake:
void Awake() {
anims = new Animator[(int)FColorType.ColorNum];
if(needShake) {
curAnim.SetTrigger("shake");
关闭fsShake
void Update() {
if(curAnim) {
AnimatorStateInfo stateInfo = curAnim.GetCurrentAnimatorStateInfo(0);
if(stateInfo.nameHash == Animator.StringToHash("Base Layer.fsShake")) {
curAnim.SetBool("shake", false);
print ("======&&&&& stop shake!!!!");
关于Animator.StringToHash函数的说明:
animator的setBool,setTrigger等函数都有两种参数形式,一个接收string,一个接收hash;其实Animator内部是使用hash来记录相应信息的,所以接收string类型的函数内部会帮你调用StringToHash这个函数;所以如果要经常调用setTrigger等,请把参数名称hash化保持以便反复使用,从而提高性能。
在状态机animator中获取animation state 和animation clip的方法(参考):
public static AnimationClip getAnimationClip(Animator anim, string clipName) {
UnityEditorInternal.State state = getAnimationState(anim, clipName);
return state!=null ? state.GetMotion() as AnimationClip :
public static UnityEditorInternal.State getAnimationState(Animator anim, string clipName) {
UnityEditorInternal.State state =
if(anim != null) {
UnityEditorInternal.AnimatorController ac = anim.runtimeAnimatorController as UnityEditorInternal.AnimatorC
UnityEditorInternal.StateMachine sm = ac.GetLayer(0).stateM
for(int i = 0; i & sm.stateC i++) {
UnityEditorInternal.State _state = sm.GetState(i);
if(state.uniqueName.EndsWith("." + clipName)) {
6. scene的切换
同步方式:
Application.LoadLevel(currentName);
异步方式:
Application.LoadLevelAsync("ARScene");
7. 加载资源
Resources.Load&Texture&(string.Format("{0}{1:D2}", mPrefix, 5));
8. Tag VS. Layer
-& Tag用来查询对象
-& Layer用来确定哪些物体可以被raycast,还有用在camera render中
transform.eulerAngles 可以访问 rotate的 xyz
transform.RotateAround(pivotTransVector, Vector3.up, -0.5f * (tmp-preX) * speed);
10. 保存数据
PlayerPrefs.SetInt("isInit_" + Application.loadedLevelName, 1);
11. 动画编码
http://www.cnblogs.com/lopezycj/archive//Unity3d_AnimationEvent.html
http://game.ceeger.com/Components/animeditor-AnimationEvents.html
http://answers.unity3d.com/questions/8172/how-to-add-new-curves-or-animation-events-to-an-im.html
12. 遍历子对象
Transform[] transforms = target.GetComponentsInChildren&Transform&();
for (int i = 0, imax = transforms.L i & ++i) {
Transform t = transforms[i];
t.gameObject.SendMessage(functionName, gameObject, SendMessageOptions.DontRequireReceiver);
13. 音效的播放
先添加Auido Source, 设置Audio Clip, 也可以在代码中加入。然后在代码中调用audio.Play(), 参考如下代码:
public AudioClip aC
void Start () {
audio.clip = aC
audio.Play();
另外,如果是3d音效的话,需要调整audio Souce中的panLevel才能听到声音,不清楚原因。
14. 调试技巧(Debug)
可以在OnDrawGizmos函数来进行矩形区域等,达到调试的目的,请参考NGUI中的UIDraggablePanel.cs文件中的那个函数实现。
#if UNITY_EDITOR
/// &summary&
/// Draw a visible orange outline of the bounds.
/// &/summary&
void OnDrawGizmos ()
if (mPanel != null)
Bounds b =
Gizmos.matrix = transform.localToWorldM
Gizmos.color = new Color(1f, 0.4f, 0f);
Gizmos.DrawWireCube(new Vector3(b.center.x, b.center.y, b.min.z), new Vector3(b.size.x, b.size.y, 0f));
15. 延时相关( StartCoroutine)
StartCoroutine(DestoryPlayer());
IEnumerator DestoryPlayer() {
Instantiate(explosionPrefab, transform.position, transform.rotation);
gameObject.renderer.enabled =
yield return new WaitForSeconds(1.5f);
gameObject.renderer.enabled =
16. Random做种子
UnityEngine.Random.seed = (int)System.DateTime.Now.ToUniversalTime().ToBinary();
调试技巧(debug),可以把值方便地在界面上打印出来
void OnGUI() {
GUI.contentColor = Color.
GUILayout.Label("deltaTime is: " + Time.deltaTime);
}18. 分发消息
sendMessage, BroadcastMessage等
19. 游戏暂停(对timeScale进行设置)
Time.timeScale = 0;
20. 实例化一个prefab
Rigidbody2D propInstance = Instantiate(backgroundProp, spawnPos, Quaternion.identity) as Rigidbody2D;
21. Lerp函数的使用场景
// Set the health bar's colour to proportion of the way between green and red based on the player's health.
healthBar.material.color = Color.Lerp(Color.green, Color.red, 1 - health * 0.01f);
22. 在特定位置播放声音
// Play the bomb laying sound.
AudioSource.PlayClipAtPoint(bombsAway,transform.position);
23. 浮点数相等的判断
(由于浮点数有误差, 所以判断的时候最好不要用等号,尤其是计算出来的结果)
if (Mathf.Approximately(1.0, 10.0/10.0))
print ("same");
24. 通过脚本修改shader中uniform的值
//shader的写法
Properties {
disHeight ("threshold distance", Float) = 3
SubShader {
#pragma vertex vert
#pragma fragment frag
uniform float disH
// ===================================
// 修改shader中的disHeight的值
gameObject.renderer.sharedMaterial.SetFloat("disHeight", height);
25. 获取当前level的名称
Application.loadedLevelName
26. 双击事件
void OnGUI() {
Event Mouse = Event.
if ( Mouse.isMouse && Mouse.type == EventType.MouseDown && Mouse.clickCount == 2) {
print("Double Click");
}27. 日期:
System.DateTime dd = System.DateTime.N
GUILayout.Label(dd.ToString("M/d/yyyy"));
28. RootAnimation中移动的脚本处理
class RootControl : MonoBehaviour {
void OnAnimatorMove() {
Animator anim = GetComponent&Animator&();
if(anim) {
Vector3 newPos = transform.
newPos.z += anim.GetFloat("Runspeed") * Time.deltaT
transform.position = newP
29. BillBoard效果
(广告牌效果,或者向日葵效果,使得对象重视面向摄像机)
public class BillBoard : MonoBehaviour {
// Update is called once per frame
void Update () {
transform.LookAt(Camera.main.transform.position, -Vector3.up);
另外,Shader的实现方案请参考:
30. script中的属性编辑器
(Property Drawers),还可以自定义属性编辑器
其中Popup好像无效,但是enum类型的变量,能够达到Popup的效果
public class Example : MonoBehaviour {
public string playerName = "Unnamed";
[Multiline]
public string playerBiography = "Please enter your biography";
[Popup ("Warrior", "Mage", "Archer", "Ninja")]
public string @class = "Warrior";
[Popup ("Human/Local", "Human/Network", "AI/Easy", "AI/Normal", "AI/Hard")]
[Range (0, 100)]
public float health = 100;
[Regex (@"^(?:\d{1,3}\.){3}\d{1,3}$", "Invalid IP address!\nExample: '127.0.0.1'")]
public string serverAddress = "192.168.0.1";
public Vector3 forward = Vector3.
public Vector3 target = new Vector3 (100, 200, 300);
public ScaledC
public ScaledC
public float turnRate = (Mathf.PI / 3) * 2;
31. Mobile下面使用lightmapping问题的解决方案
在mobile模式下,lightmapping可能没有反应,可以尝试使用mobile下的shader,可以解决问题。更多请参考:
Unity下画线的功能(用于debug)
Debug.DrawLine (Vector3.zero, new Vector3 (10, 0, 0), Color.red);33. Shader中代码的复用(CGINCLUDE的使用)
Shader "Self-Illumin/AngryBots/InterlacePatternAdditive" {
Properties {
_MainTex ("Base", 2D) = "white" {}
#include "UnityCG.cginc"
sampler2D _MainT
struct v2f {
half4 pos : SV_POSITION;
half2 uv : TEXCOORD0;
half2 uv2 : TEXCOORD1;
v2f vert(appdata_full v) {
fixed4 frag( v2f i ) : COLOR {
return colorT
SubShader {
Tags {"RenderType" = "Transparent" "Queue" = "Transparent" "Reflection" = "RenderReflectionTransparentAdd" }
ZWrite Off
Blend One One
#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
FallBack Off
34. 获取AnimationCurve的时长
_curve.keys[_curve.length-1].
35. C#中string转变成byte[]:
byte[] b1 = System.Text.Encoding.UTF8.GetBytes (myString);
byte[] b2 = System.Text.Encoding.ASCII.GetBytes (myString);
System.Text.Encoding.Default.GetBytes(sPara)
new ASCIIEncoding().GetBytes(cpara);
char[] cpara=new char[bpara.length];
for(int i=0;i &bpara.i ++){char[i]=system.convert.tochar(bpara[i]);}
list.Sort(delegate(Object a, Object b) { return a.name.CompareTo(b.name); });
37. NGUI的相关类关系:
38. 使得脚本能够在editor中实时反映:
在脚本前加上:[ExecuteInEditMode], 参考UISprite。
39. 隐藏相关属性
属性前加上 [HideInInspector],在shader中也适用;
public class ResourceLoad : MonoBehaviour {
[HideInInspector] public string ressName = "Sphere";
public string baseUrl = "http://192.168.56.101/ResUpdate/{0}.assetbundle";Shader "stalendp/imageShine" {
Properties {
[HideInInspector] _image ("image", 2D) = "white" {}
_percent ("_percent", Range(-5, 5)) = 1
_angle("_angle", Range(0, 1)) = 0
40. 属性的序列化
可被序列化的属性,可以显示在Inspector面板上(可以使用HideInInspector来隐藏);public属性默认是可被序列化的,private默认是不可序列化的。使得private属性可被序列化,可以使用[SerializeField]来修饰。如下:
[SerializeField] private string ressName = "Sphere";
41. Shader编译的多样化()
shader通常如下的写法:
#pragma multi_compile FANCY_STUFF_OFF FANCY_STUFF_ON
这样可以把Shader编译成多个版本。使用的时候,局部设置Material.EnableKeyword, DisableKeyword;或则 全局设置Shader.EnableKeyword and DisableKeyword进行设置。
42. 多个scene共享内容
void Awake() {
DontDestroyOnLoad(transform.gameObject);
}43. 使用Animation播放unity制作的AnimationClip:
首先需要设置AnimationType的类型为1 (需要在animationClip的Debug模式的属性中进行设置,如下图。另外,如果需要在animator中播放动画,需要类型为2);
代码如下:
string clipName = "currentClip";
AnimationClip clip = ...;
// 设置animationClip
if (anim == null) {
anim = gameObject.AddComponent&Animation&();
anim.AddClip(clip, clipName);
anim[clipName].speed = _speedS
// 计算时间
float duration = anim[clipName].
duration /= _speedS
// 播放动画
anim.Play(clipName);
yield return new WaitForSeconds(duration + 0.1f);
// 动画结束动作
anim.Stop();
anim.RemoveClip(clipName);
44. RenderTexture的全屏效果
MeshFilter mesh = quard.GetComponent&MeshFilter& ();
// 创建和摄像机相关的renderTexture
RenderTexture rTex = new RenderTexture ((int)cam.pixelWidth, (int)cam.pixelHeight, 16);
cam.targetTexture = rT
mesh.renderer.material.mainTexture = rTshader端:
#include "UnityCG.cginc"
sampler2D _MainT
sampler2D _NoiseT
struct v2f {
half4 pos:SV_POSITION;
half2 uv : TEXCOORD0;
float4 srcPos: TEXCOORD1;
v2f vert(appdata_full v) {
o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
o.uv = v.texcoord.
o.srcPos = ComputeScreenPos(o.pos);
fixed4 frag(v2f i) : COLOR0 {
float tmp = saturate(1-(length(i.uv-float2(0.5,0.5)))*2)*0.04;
float2 wcoord = (i.srcPos.xy/i.srcPos.w) + tex2D(_NoiseTex, i.uv) * tmp - tmp/2;
return tex2D(_MainTex, wcoord);
45)使用RenderTexture制作屏幕特效:
[ExecuteInEditMode]
public class MyScreenEffect : MonoBehaviour {
void OnRenderImage(RenderTexture source, RenderTexture dest) {
Graphics.Blit(source, dest, material);
}如果需要多次渲染,需要使用RenderTexture.GetTemporary生成临时的RenderTexture,这个方法会从unity维护的池中获取,所以在使用完RenderTexture后,尽快调用RenderTexture.ReleaseTemporary使之返回池中。 RenderTexture存在于GPU的DRAM中,具体实现可以参考Cocos2dx中的写法来理解(CCRenderTexture.cpp中有具体实现)。GPU的架构请参考:
46. 特定条件下暂停unity
在调试战斗的时候,需要在特定条件下暂停unity,以便查看一些对象的设置。可以使用Debug.Break();来达到目的。这是需要处于debug模式,才能够达到效果。
47. 在特定exception发生时暂停执行;
默认情况下,unity在遇到异常时,是不会停止执行的。但是如果要在nullReferenceException等exception发生时,进行调试。可以在MonoDevelop的菜单中选择Run/Exceptions..., 做相关设置:
48. NGUI性能建议
相关知识:1)在NGUI中,一个Panel对应一个DrawCall(当然一个panel里面的UISprite来自多个图集,就会有多个drawCall);2)当一个UISprite等UIWidget控件的active改变时,DrawCall会重新计算一遍;3)DrawCall的计算比较耗时,首先会收集DrawCall下所有UIWidget的verts,norms,trans,uvs,cols等信息,还要向GPU传输数据,相对比较耗时。
问题:当在一个Panel中有大量的UIWidget,有一部分是经常改变active的,有些部分则不怎么变。这样就会导致频繁地计算DrawCall。
性能提升方案:把经常改变active的控件单独到一个panel中。把不怎么变动的部分独立到另外的panel中。
49. NGUI中设置自定义的Shader,并改变properties的值。
使用UITexture,可以设置自定义的Material。需要注意的是,改变properties的值,需要使用UITexture中的drawCall的dynamicMaterial,如下:
UITexture tex=....;
tex.drawCall.dynamicMaterial.SetFloat("_percent", du/DU);
50. 鉴别unity中的InputTouch的类型:
public enum OperateStatus {
OS_Idle=0,
OS_Draging=1,
OS_Scaling=2
void Update () {
TouchPhase tp = Input.GetTouch(0).
if(tp==TouchPhase.Ended || tp==TouchPhase.Canceled) {
oStatus = OperateStatus.OS_I
oStatus = Input.touchCount&1 ? OperateStatus.OS_Scaling : OperateStatus.OS_D
51. 物理系统的性能提示:
Unity中涉及物理模拟的有静态碰撞(static collider)和动态碰撞(dynamic collider)。其中,静态碰撞物体是指具有collider属性但没有rigidbody的物体,动态碰撞物体是指具有collider和rigidbody属性的物体。
Unity引擎期待静态物体是静止,会把场景中的所有静态物体统一计算成一个叫static collider cache的东西来加速物理模拟。但是如果其中某个静态物体进行了移动,系统就要重新计算static collider cache;而这个代价是很大的。所以如果一个物体是要经常移动的,应该设计成动态物体,即添加rigidbody成分;至于使rigidbody不响应重力等作用力的影响,请参考rigidbody中的"Use Gravity"和“Is Kinematic”属性。
如果rigidbody是kinematic的,它不响应force,可以用来制作飞行障碍物等效果。如果不是kinematic的,就会响应foce。
参考如下官方教程最后的性能分析:
52. unity中四种Collider的对比:
类型能否移动是否接收Trigger消息是否受碰撞影响是否受物理影响Static代价大NoNoNoKinematic
RigidbodyYesYesNoNoCharacter ControllerYes未知YesNoRigidbodyYesYesYesYes仔细观察上面的表格,发现越往下,特性越多。官方在介绍collision的时候,没有加入讨论Character Controller,这个是我自己添加比较的。
另外,如果一个物体能够受碰撞影响,当然就能够接收Collition消息了。
关于接收Collision消息和Trigger消息的官方的详细表,请参考 的文末的表格。53. 法线计算相关 使一个物体依附在一个表面上,保持物体的up方向和表面的法线方向一致(物体记为obj,表面记为suf):方法1:obj.transform.rotation = Quaternion.FromToRotation(obj.transform.up, suf.transform.up)* obj.transform.方法2:Vector3 axis = Vector3.Cross(obj.transform.up, suf.transform.up);
float angle = Vector3.Angle(obj.transform.up, suf.transform.up);
obj.transform.Rotate(axis, angle, Space.World);54. AngryBots中的showFPS代码:
@script ExecuteInEditMode
private var gui : GUIT
private var updateInterval = 1.0;
private var lastInterval : // Last interval end time
private var frames = 0; // Frames over current interval
function Start()
lastInterval = Time.realtimeSinceS
frames = 0;
function OnDisable ()
DestroyImmediate (gui.gameObject);
function Update()
#if !UNITY_FLASH
var timeNow = Time.realtimeSinceS
if (timeNow & lastInterval + updateInterval)
var go : GameObject = new GameObject("FPS Display", GUIText);
go.hideFlags = HideFlags.HideAndDontS
go.transform.position = Vector3(0,0,0);
gui = go.guiT
gui.pixelOffset = Vector2(5,55);
var fps : float = frames / (timeNow - lastInterval);
var ms : float = 1000.0f / Mathf.Max (fps, 0.00001);
gui.text = ms.ToString("f1") + "ms " + fps.ToString("f2") + "FPS";
frames = 0;
lastInterval = timeN
55. 关于Hierarchy中按名称的字母排序功能:
public class AlphaNumericSort : BaseHierarchySort
public override int Compare(GameObject lhs, GameObject rhs)
if (lhs == rhs) return 0;
if (lhs == null) return -1;
if (rhs == null) return 1;
return EditorUtility.NaturalCompare(lhs.name, rhs.name);
}把上面的代码放到工程中之后,在Hierarchy中就会出现排序的按钮,如下:
BaseHierarchySort的官方地址:
56. 用脚本在Mac下打开多个Unity工程:
默认到情况下,Mac中只能够允许一个Unity实例。但是通过脚本(把工程路径写到Unity启动参数中)可以方便地打开多个常用的工程(参考:)
#!/bin/bash
/Applications/Unity/Unity.app/Contents/MacOS/Unity -projectPath "/path/to/your/projectA"57. 在Mac启动多个Unity实例:
a)设置Unity启动时显示对话框。具体做法=》确保如下选择打勾:Unity Perferences/General/Always Show Project W
b)从命令行运行unity,并提供参数(这里参数“11”是随意写的,作用是让Mac启动一个新的进程,末尾的“&”表示后台启动进程):
/Applications/Unity5/Unity5.app/Contents/MacOS/Unity 11 &c)写成脚本行形式(脚本名称为:startUnity5),方便启动:#!/bin/bash
/Applications/Unity5/Unity5.app/Contents/MacOS/Unity 11 &d)运行脚本当然首先要设置脚本为可运行的,命令如下:sudo chmod +x startUnity5运行脚本:./startUnity5
相关文章:
没有更多推荐了,}

我要回帖

更多关于 剑三编辑器非法路径 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信