位置: 编程技术 - 正文

【Unity】技巧集合(unity操作教程)

编辑:rootadmin

推荐整理分享【Unity】技巧集合(unity操作教程),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:unity_jail,unity小技巧,unity小技巧,unity ulua,unity ulua,unity-,unity-,unity-,内容如对您有帮助,希望把文章链接给更多的朋友!

转载: “Hierarchy”中复制相关对象树,暂停游戏后替换原来的,就可以了。(其实这个拷贝过程是序列化过程,这种方法是序列化到内存中;另外一种方法就是序列化到磁盘上,即把内容拖动到文件夹中变成prefab,效果也是一样的)

2)Layer的用法

LayerMask.NameToLayer("Ground"); // 通过名字获取layer

3D Raycast

[csharp] view plaincopyRaycastHit hit; if(Physics.Raycast(cam3d.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, (1<<LayerMask.NameToLayer("Ground")))) { ... }

2D Raycast

[csharp] view plaincopyCollider2D h = Physics2D.OverlapPoint(cam2d.ScreenToWorldPoint(Input.mousePosition), (1<<LayerMask.NameToLayer("xxx"))); if(h) { ... }

3)物理摄像头取色(WebCamTexture)

[csharp] view plaincopyTexture2D 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(); return snap; }

保存截图:

[csharp] view plaincopySystem.IO.File.WriteAllBytes(Application.dataPath &#; "/test.png", exactCamData().EncodeToPNG());

4) 操作componenent

添加:

[csharp] view plaincopyCircleCollider2D cld = (CircleCollider2D)colorYuan[i].AddComponent(typeof(CircleCollider2D)); cld.radius = 1;

删除:

[csharp] view plaincopyDestroy(transform.gameObject.GetComponent<SpriteRenderer>());

5)动画相关

状态Init到状态fsShake的的条件为:参数shake==true;代码中的写法:

触发fsShake:

[csharp] view plaincopyvoid Awake() { anims = new Animator[(int)FColorType.ColorNum]; } .... if(needShake) { curAnim.SetTrigger("shake"); } 关闭fsShake

[csharp] view plaincopyvoid Update() { .... if(curAnim) { AnimatorStateInfo stateInfo = curAnim.GetCurrentAnimatorStateInfo(0); if(stateInfo.nameHash == Animator.StringToHash("Base Layer.fsShake")) { curAnim.SetBool("shake", false); curAnim = null; print ("======>>>>> stop shake!!!!"); } } .... }

关于Animator.StringToHash函数的说明:

animator的setBool,setTrigger等函数都有两种参数形式,一个接收string,一个接收hash;其实Animator内部是使用hash来记录相应信息的,所以接收string类型的函数内部会帮你调用StringToHash这个函数;所以如果要经常调用setTrigger等,请把参数名称hash化保持以便反复使用,从而提高性能。

在状态机animator中获取animation state 和animation clip的方法(参考 view plaincopypublic static AnimationClip getAnimationClip(Animator anim, string clipName) { UnityEditorInternal.State state = getAnimationState(anim, clipName); return state!=null ? state.GetMotion() as AnimationClip : null; } public static UnityEditorInternal.State getAnimationState(Animator anim, string clipName) { UnityEditorInternal.State state = null; if(anim != null) { UnityEditorInternal.AnimatorController ac = anim.runtimeAnimatorController as UnityEditorInternal.AnimatorController; UnityEditorInternal.StateMachine sm = ac.GetLayer(0).stateMachine; for(int i = 0; i < sm.stateCount; i&#;&#;) { UnityEditorInternal.State _state = sm.GetState(i); if(state.uniqueName.EndsWith("." &#; clipName)) { state = _state; } } } return state; }

6)scene的切换

同步方式:

[csharp] view plaincopyApplication.LoadLevel(currentName);

异步方式:

[csharp] view plaincopyApplication.LoadLevelAsync("ARScene");

7)加载资源

[csharp] view plaincopyResources.Load<Texture>(string.Format("{0}{1:D2}", mPrefix, 5));

8)Tag VS. Layer

-> Tag用来查询对象

-> Layer用来确定哪些物体可以被raycast,还有用在camera render中

9)旋转

transform.eulerAngles 可以访问 rotate的 xyz

[csharp] view plaincopytransform.RotateAround(pivotTransVector, Vector3.up, -0.5f * (tmp-preX) * speed); )保存数据[csharp] view plaincopyPlayerPrefs.SetInt("isInit_" &#; Application.loadedLevelName, 1);

)动画编码

遍历子对象

[csharp] view plaincopyTransform[] transforms = target.GetComponentsInChildren<Transform>(); for (int i = 0, imax = transforms.Length; i < imax; &#;&#;i) { Transform t = transforms[i]; t.gameObject.SendMessage(functionName, gameObject, SendMessageOptions.DontRequireReceiver); }

)音效的播放

先添加Auido Source, 设置Audio Clip, 也可以在代码中加入。然后在代码中调用audio.Play(), 参考如下代码:

[csharp] view plaincopypublic AudioClip aClip; ... void Start () { ... audio.clip = aClips; audio.Play(); ... }

另外,如果是3d音效的话,需要调整audio Souce中的panLevel才能听到声音,不清楚原因。

【Unity】技巧集合(unity操作教程)

)调试技巧(Debug)

可以在OnDrawGizmos函数来进行矩形区域等,达到调试的目的,请参考NGUI中的UIDraggablePanel.cs文件中的那个函数实现。

[csharp] view plaincopy#if UNITY_EDITOR /// <summary> /// Draw a visible orange outline of the bounds. /// </summary> void OnDrawGizmos () { if (mPanel != null) { Bounds b = bounds; Gizmos.matrix = transform.localToWorldMatrix; 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)); } } #endif

)延时相关( StartCoroutine)

[csharp] view plaincopyStartCoroutine(DestoryPlayer()); ... IEnumerator DestoryPlayer() { Instantiate(explosionPrefab, transform.position, transform.rotation); gameObject.renderer.enabled = false; yield return new WaitForSeconds(1.5f); gameObject.renderer.enabled = true; }

)Random做种子

[csharp] view plaincopyRandom.seed = System.Environment.TickCount; 或者 Random.seed = System.DateTime.Today.Millisecond;

) 调试技巧(debug),可以把&#;方便地在界面上打印出来

[csharp] view plaincopyvoid OnGUI() { GUI.contentColor = Color.green; GUILayout.Label("deltaTime is: " &#; Time.deltaTime); } )分发消息

sendMessage, BroadcastMessage等

) 游戏暂停(对timeScale进行设置)

[csharp] view plaincopyTime.timeScale = 0;

) 实例化一个prefab

[csharp] view plaincopyRigidbody2D propInstance = Instantiate(backgroundProp, spawnPos, Quaternion.identity) as Rigidbody2D;

)Lerp函数的使用场景

[csharp] view plaincopy// 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.f);

)在特定位置播放声音

[csharp] view plaincopy// Play the bomb laying sound. AudioSource.PlayClipAtPoint(bombsAway,transform.position);

) 浮点数相等的判断(由于浮点数有误差, 所以判断的时候最好不要用等号,尤其是计算出来的结果)

[csharp] view plaincopyif (Mathf.Approximately(1.0, .0/.0)) print ("same");

)通过脚本修改shader中uniform的&#;

[csharp] view plaincopy//shader的写法 Properties { ... disHeight ("threshold distance", Float) = 3 } SubShader { Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag ... uniform float disHeight; ... // =================================== // 修改shader中的disHeight的&#; gameObject.renderer.sharedMaterial.SetFloat("disHeight", height);

) 获取当前level的名称

[csharp] view plaincopyApplication.loadedLevelName

)双击事件

[csharp] view plaincopyvoid OnGUI() { Event Mouse = Event.current; if ( Mouse.isMouse && Mouse.type == EventType.MouseDown && Mouse.clickCount == 2) { print("Double Click"); } }

) 日期:

[csharp] view plaincopySystem.DateTime dd = System.DateTime.Now; GUILayout.Label(dd.ToString("M/d/yyyy"));

) RootAnimation中移动的脚本处理

[csharp] view plaincopyclass RootControl : MonoBehaviour { void OnAnimatorMove() { Animator anim = GetComponent<Animator>(); if(anim) { Vector3 newPos = transform.position; newPos.z &#;= anim.GetFloat("Runspeed") * Time.deltaTime; transform.position = newPos; } } }

) BillBoard效果(广告牌效果,或者向日葵效果,使得对象重视面向摄像机)

[csharp] view plaincopypublic class BillBoard : MonoBehaviour { // Update is called once per frame void Update () { transform.LookAt(Camera.main.transform.position, -Vector3.up); } }

)script中的属性编辑器(Property Drawers),还可以自定义属性编辑器

参考: view plaincopypublic 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")] public string controller; [Range (0, )] public float health = ; [Regex (@"^(?:d{1,3}.){3}d{1,3}$", "Invalid IP address!nExample: '.0.0.1'")] public string serverAddress = "..0.1"; [Compact] public Vector3 forward = Vector3.forward; [Compact] public Vector3 target = new Vector3 (, , ); public ScaledCurve range; public ScaledCurve falloff; [Angle] public float turnRate = (Mathf.PI / 3) * 2; }

)Mobile下面使用lightmapping问题的解决方案

在mobile模式下,lightmapping可能没有反应,可以尝试使用mobile下的shader,可以解决问题。更多请参考: Unity下画线的功能(用于debug)

[csharp] view plaincopyDebug.DrawLine (Vector3.zero, new Vector3 (, 0, 0), Color.red);

)Shader中代码的复用(CGINCLUDE的使用)

[cpp] view plaincopyShader "Self-Illumin/AngryBots/InterlacePatternAdditive" { Properties { _MainTex ("Base", 2D) = "white" {} //... } CGINCLUDE #include "UnityCG.cginc" sampler2D _MainTex; //... struct v2f { half4 pos : SV_POSITION; half2 uv : TEXCOORD0; half2 uv2 : TEXCOORD1; }; v2f vert(appdata_full v) { v2f o; // ... return o; } fixed4 frag( v2f i ) : COLOR { // ... return colorTex; } ENDCG SubShader { Tags {"RenderType" = "Transparent" "Queue" = "Transparent" "Reflection" = "RenderReflectionTransparentAdd" } Cull Off ZWrite Off Blend One One Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #pragma fragmentoption ARB_precision_hint_fastest ENDCG } } FallBack Off }

)获取AnimationCurve的时长

[csharp] view plaincopy_curve.keys[_curve.length-1].time;

)C#中string转变成byte[]:

[csharp] view plaincopybyte[] 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.length;i &#;&#;){char[i]=system.convert.tochar(bpara[i]);}

) 排序

[csharp] view plaincopylist.Sort(delegate(Object a, Object b) { return a.name.CompareTo(b.name); });

) NGUI的相关类关系:

)使得脚本能够在editor中实时反映:

在脚本前加上:[ExecuteInEditMode], 参考UISprite。

)隐藏相关属性

属性前加上 [HideInInspector],在shader中也适用;

比如:

[csharp] view plaincopypublic class ResourceLoad : MonoBehaviour { [HideInInspector] public string ressName = "Sphere"; public string baseUrl = " [csharp] view plaincopyShader "stalendp/imageShine" { Properties { [HideInInspector] _image ("image", 2D) = "white" {} _percent ("_percent", Range(-5, 5)) = 1 _angle("_angle", Range(0, 1)) = 0 }

)属性的序列化

可被序列化的属性,可以显示在Inspector面板上(可以使用HideInInspector来隐藏);public属性默认是可被序列化的,private默认是不可序列化的。使得private属性可被序列化,可以使用[SerializeField]来修饰。如下:

[csharp] view plaincopy[SerializeField] private string ressName = "Sphere";

)Shader编译的多样化(Making multiple shader program variants)

shader通常如下的写法:

)AngryBots中的showFPS代码:

Unity3d实现的十字路口的模拟(四) ok,我们已经知道我们的预制物体都是怎么个结构了,下面我们就来说一下,具体的随机创造车辆的函数,我是把这个脚本放到了我的地形这个物体上,

Unity3d实现的十字路口的模拟(五) 这一节我们来说一下红绿灯的控制和总结一下经验。红绿灯的模型,本来也是想要在网上下载结果找来半天没有找到相应的资源,于是就自己用3dmax做了

Unity3D 4.6.3之游戏物体的激活与暂停 在游戏开发时有时会将游戏物体激活或者暂停以达到预期效果,但是当临时用GameObject.Find(gameobject).setActive(false)暂停游戏物体后,若在其他地方再想通过

标签: unity操作教程

本文链接地址:https://www.jiuchutong.com/biancheng/380101.html 转载请保留说明!

上一篇:Unity3d实现的十字路口的模拟(二)(unity3d功能介绍)

下一篇:Unity3d实现的十字路口的模拟(四)(u3d unity3d)

  • PHP使用mkdir创建多级目录的方法(php中用来创建目录的函数是)

    PHP使用mkdir创建多级目录的方法(php中用来创建目录的函数是)

  • 根据key删除数组中指定的元素实现方法(删除数组中某个值的数)

    根据key删除数组中指定的元素实现方法(删除数组中某个值的数)

  • sql语句中单引号嵌套问题(一定要避免直接嵌套)(sql语句中单引号是什么)

    比如下面例子是存储过程里查询时的语句示例

    红色部分是会报错的,应该写成 @condition= 'ROOMTYPElike ‘ ‘%标准间%' ‘ ', 蓝色部分不是双引号,而是两个单引号

    谈谈sqlserver自定义函数与存储过程的区别 一、自定义函数:1.可以返回表变量2.限制颇多,包括不能使用output参数;不能用临时表;函数内部的操作不能影响到外部环境;不能通过select返回结果

    深入分析SqlServer查询计划 对于SQLServer的优化来说,优化查询可能是很常见的事情。由于数据库的优化,本身也是一个涉及面比较的广的话题,因此本文只谈优化查询时如何看懂SQ

    sql 判断字符串中是否包含数字和字母的方法 判断是否含有字母selectPATINDEX('%[A-Za-z]%',‘ads')=0(如果存在字母,结果1)判断是否含有数字PATINDEX('%[0-9]%',‘sdf" class="img-responsive" alt="sql语句中单引号嵌套问题(一定要避免直接嵌套)(sql语句中单引号是什么)">

    sql语句中单引号嵌套问题(一定要避免直接嵌套)(sql语句中单引号是什么)

  • win2008 enterprise R2 x64 中安装SQL server 2008的方法

    win2008 enterprise R2 x64 中安装SQL server 2008的方法

  • 编写高质量代码改善C#程序——使用泛型集合代替非泛型集合(建议20)(编写高质量代码改善JAVA程序的151个建议)

    编写高质量代码改善C#程序——使用泛型集合代替非泛型集合(建议20)(编写高质量代码改善JAVA程序的151个建议)

  • Mac怎么卸载Java?在Mac上卸载Java应用程序的方法介绍(macos卸载java)

    Mac怎么卸载Java?在Mac上卸载Java应用程序的方法介绍(macos卸载java)

  • win7系统ctfmon.exe进程是什么?详解ctfmon.exe进程的作用(win7系统ctfmon在哪个文件夹)

    win7系统ctfmon.exe进程是什么?详解ctfmon.exe进程的作用(win7系统ctfmon在哪个文件夹)

  • 第七章之菜单按钮图标组件(菜单下一章)

    第七章之菜单按钮图标组件(菜单下一章)

  • 高级 Unity3d 手机脚本(unitystudio手机版)

    高级 Unity3d 手机脚本(unitystudio手机版)

  • Python实现列表转换成字典数据结构的方法(python怎么将列表转换成数字)

    Python实现列表转换成字典数据结构的方法(python怎么将列表转换成数字)

  • 居民个人的综合所得
  • 转让股份的印花税怎么交
  • 营业总收入包含投资收益吗
  • 增值税进项发票网上勾选平台
  • 啤酒消费税在那里征收
  • 折旧费计算主要有几种方法?分别有什么特点?
  • 开发票要多交费正常吗?
  • 代发工资记什么科目
  • 认缴注册资本的风险
  • 跨期发票可以申报抵扣进项税额吗?
  • 按公允价值计量是什么意思
  • 免税销售额扣除项目本期实际扣除额
  • 卫生巾的税率
  • 会议费报销注意事项
  • 烟草企业发生的广告和宣传费在当年营业收入15
  • 营增改后,建筑施工企业有哪些改变?
  • 个体户进项发票多开出发票少怎么办
  • 城建税和教育费附加可以税前扣除吗
  • 工程施工什么时候确认收入
  • 我的初级备考经验,认真就有收获
  • 维修开票单位写什么
  • 光伏发电项目发电户是否可以享受小规模优惠政策
  • 财产清查的会计分录
  • 资金筹集业务的账务处理重点笔记
  • 个人业务费是什么
  • 主营业务收入平均增长率计算公式近两年
  • 信用卡扣手续费怎么算的
  • linux怎么更改账户名
  • 共用水电无法取水怎么办
  • 股权收购特殊性税务处理案例
  • 补充养老保险的特点
  • 埃姆雷莫尔
  • 免税的农业企业可以抵扣专票吗
  • 免税需要什么条件
  • 小规模企业现金怎样管理
  • vue知识点汇总
  • 数学建模心态崩了
  • 一文看懂华为新品发布会
  • 盈余公积金的账务处理
  • 循环表是线性表吗
  • wordpress怎么降级
  • mysql存二进制用哪个字段
  • 股东入股资金如何记账
  • 为什么费用报销先由主管部门审批在由财务审核
  • 兼职属于劳务关系吗
  • 个体户逾期未报年报后补报了怎么办
  • 公司注销公章的处理
  • 材料暂估入库的附件需要哪些资料
  • 企业逾期贷款利息影响征信吗
  • 低值易耗品摊销借贷方向
  • 应付款多付了不可退回怎么做会计分录
  • 给股东分利润怎么做账
  • 同城票据交换差额户金额从哪得来的
  • 销项发票导出为什么是乱码
  • 暂领款是什么意思
  • 库存现金过多的隐患
  • mysql外键怎么写
  • 在centos上安装ftp服务应运行指令
  • sql替换快捷键
  • 在windows七中
  • win8系统怎么设置
  • centos8指令
  • win10系统最新版用户维护在哪
  • 怎样设置Win XP下安装打印机驱动程序
  • centos7搭建lamp 详细
  • win8引导盘
  • shell中创建文件
  • javascriptz
  • node.js基础入门
  • 无线adb调试开关下载
  • python生成器怎么用
  • 如何改变this指向
  • js怎么输出文字
  • JavaScript中reduce()方法的使用详解
  • NGUI之UITexture
  • 国家税务12366电子税务局重庆
  • 2021边疆补助什么时候下来
  • 种植业税收优惠政策2023
  • 怎么查询地税信息表
  • 个人的车租给公司保险可以入账吗
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设