位置: 编程技术 - 正文

Unity技巧集合(unity如何合并物体)

编辑:rootadmin

推荐整理分享Unity技巧集合(unity如何合并物体),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:unity怎么组合,unity 集合,unity合并,unity组合,unity quit,unitylist,unity 集合,unity怎么组合,内容如对您有帮助,希望把文章链接给更多的朋友!

这篇文章将收集unity的相关技巧,会不断地更新内容。

1)保存运行中的状态

unity在运行状态时是不能够保存的。但在运行时编辑的时候,有时会发现比较好的效果想保存。这时可以在 “Hierarchy”中复制相关对象树,暂停游戏后替换原来的,就可以了。

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.AddComponent(typeof(CircleCollider2D));cld.radius = 1;

删除:

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

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!!!!"); }}....}

6)scene的切换

同步方式:

[csharp] view plaincopyApplication.LoadLevel(currentName);

异步方式:

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

7)加载资源

[csharp] view plaincopyResources.Load(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[tr]();for (int i = 0, imax = transforms.Length; i < imax; &#;&#;i) { Transform t = transforms; 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才能听到声音,不清楚原因。

)调试技巧(Debug)

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

[csharp] view plaincopy#if UNITY_EDITOR /// /// Draw a visible orange outline of the bounds. /// 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;Unity技巧集合(unity如何合并物体)

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

[csharp] view plaincopyvoid OnGUI() { 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(); 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),还可以自定义属性编辑器

【狗刨学习网】

其中Popup好像无效,但是enum类型的变量,能够达到Popup的效果

[csharp] 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!Example: '.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="system.convert.tochar(bpara);}"

) 排序

[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 = " 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通常如下的写法:

#pragma multi_compile FANCY_STUFF_OFF FANCY_STUFF_ON 这样可以把Shader编译成多个版本。使用的时候,局部设置Material.EnableKeyword, DisableKeyword;或则 全局设置Shader.EnableKeyword and DisableKeyword进行设置。)多个scene共享内容[csharp] view plaincopyvoid Awake() { DontDestroyOnLoad(transform.gameObject);}) 使用Animation播放unity制作的AnimationClip:首先需要设置AnimationType的类型为1 (需要在animationClip的Debug模式的属性中进行设置,如下图。另外,如果需要在animator中播放动画,需要类型为2); 代码如下:[csharp] view plaincopystring clipName = "currentClip";AnimationClip clip = ...;// 设置animationClipif (anim == null) { anim = gameObject.AddComponent();}anim.AddClip(clip, clipName);anim[clipName].speed = _speedScale;// 计算时间float duration = anim[clipName].length;duration /= _speedScale;// 播放动画anim.Play(clipName);yield return new WaitForSeconds(duration &#; 0.1f);// 动画结束动作anim.Stop();anim.RemoveClip(clipName);) RenderTexture的全屏效果cs端:[csharp] view plaincopyMeshFilter mesh = quard.GetComponent ();// 创建和摄像机相关的renderTextureRenderTexture rTex = new RenderTexture ((int)cam.pixelWidth, (int)cam.pixelHeight, );cam.targetTexture = rTex;mesh.renderer.material.mainTexture = rTex;shader端:[csharp] view plaincopy#include "UnityCG.cginc"sampler2D _MainTex;sampler2D _NoiseTex;struct v2f { half4 pos:SV_POSITION; half2 uv : TEXCOORD0; float4 srcPos: TEXCOORD1;};v2f vert(appdata_full v) { v2f o; o.pos = mul (UNITY_MATRIX_MVP, v.vertex); o.uv = v.texcoord.xy; o.srcPos = ComputeScreenPos(o.pos); return o;}fixed4 frag(v2f i) : COLOR0 { float tmp = saturate(1-(length(i.uv-float2(0.5,0.5)))*2)*0.; float2 wcoord = (i.srcPos.xy/i.srcPos.w) &#; tex2D(_NoiseTex, i.uv) * tmp - tmp/2; return tex2D(_MainTex, wcoord);})使用RenderTexture制作屏幕特效:[csharp] view plaincopy[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的架构 特定条件下暂停unity在调试战斗的时候,需要在特定条件下暂停unity,以便查看一些对象的设置。可以使用Debug.Break();来达到目的。这是需要处于debug模式,才能够达到效果。)在特定exception发生时暂停执行;默认情况下,unity在遇到异常时,是不会停止执行的。但是如果要在nullReferenceException等exception发生时,进行调试。可以在MonoDevelop的菜单中选择Run/Exceptions..., 做相关设置

Unity3D游戏开发之详解 Animation类和Animator类 Unity3D游戏开发之详解Animation类和Animator类Animation类animation组件用于播放动画。可以指定动画剪辑到动画组件并从脚本控制动画播放。在Unity的动画系统基

教你怎样用unity3d发布一个Android的apk文件 初识unity3d已经有一段时间了。大约那是年的暑假。无意从手机上搜到了这个引擎。从今以后我就喜欢上他了。然后又从网上找了许多关于unity资料。

最好用Unity粒子系统组件主要参数浅析 先上传一个网上流传比较多的参数解析图吧看完图,然后来看看我个人的一些理解吧~【狗刨学习网】EllipsoidParticleEmitter(这里以椭球形粒子发射器为例

标签: unity如何合并物体

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

上一篇:C#程序员整理的Unity 3D笔记(九):Unity 3D测试浅析(c#程序代码大全)

下一篇:Unity3D游戏开发之详解 Animation类和Animator类(Unity3D游戏开发pdf)

  • 残疾人就业保障金
  • 钢铁租赁公司
  • 去年的亏损今年第一季度可以弥补吗
  • 购买厨房用品属于什么费用
  • 展示费是业务宣传费吗
  • 失业保险稳岗返还是政府补助吗
  • 所有者投入的资本属于什么科目
  • 外商投资企业啥意思
  • 厂房面积测绘收费标准
  • 公司收到的其他发票
  • 设备维修费怎么入账
  • 实收资本转出计入什么科目
  • 经济社会中民商是什么
  • 完税凭证丢失如何补办
  • 进项税额大于销项税额怎么办
  • 物业营改增什么时候开始
  • 房产中介如何收取中介费
  • 原材料到半成品分录
  • 鸿蒙系统大文件夹怎么调节大小
  • 无法删除文件提示怎么办
  • 资产负债表中资产等于什么
  • 加计抵减怎么做账务处理小企业会计准则
  • 腾讯手游助手如何退出登录
  • 搜索特定
  • 让记事本文件自动删除
  • 生产车间工人发放福利
  • 安装win7前需要手动格式化c盘吗
  • win7系统怎么设置最佳性能
  • 餐饮企业库存盘点表
  • 货物发生非正常损失为什么要做j进项转出
  • 让税务局代开的发票直接交纳的税金怎么做会计分录?
  • CodeIgniter连贯操作的底层原理分析
  • php function函数的用法
  • c++好学
  • yolov3图像识别
  • 一般纳税人销售自己使用过的汽车
  • 净化器 ccm
  • php的序列化操作生成的哪种格式
  • 购买方纳税人信息与第三方信息不符
  • 商品流通的企业
  • 事业单位营业执照
  • 合伙结算转借款
  • viite
  • 月末库存商品结转成本怎么算
  • 个人福利要交税吗
  • php底部导航代码
  • 主营业务成本应交税费
  • 子公司注销时的账务处理
  • 深入理解计算机系统
  • mysql正则表达式匹配数字
  • 公司的备用金属怎么处理
  • 短期借款的实际利率与现金折扣的关系
  • 公司办理宽带套餐合法吗
  • 超过诉讼时效的法律后果
  • 两个企业同一个法人
  • 收不回来的应收账款会计分录
  • 小规模企业与一般纳税人企业最新划分标准及税率
  • 超市代销如何分成
  • 开个人普票需要身份证吗
  • 存货售出时可以冲减资产减值损失吗
  • 流动资产合计怎么算
  • Linux下mysql 5.6.17 安装图文教程
  • sql语句的优化方式
  • win10下mysql 5.7.17 zip压缩包版安装教程
  • Windows Server 2008网络中顺畅访问“邻居”
  • 无法打开vmx86
  • mac的vmware
  • Windows update更新服务启动被拒绝访问
  • linux系统chmod用法
  • win8/10功能
  • 在mac中运行exe
  • cs1.6 linux
  • linux中快捷键
  • 没有协议盒可以设置协议吗
  • cocos2d-x教程
  • js实现瀑布流效果
  • 如何理解计算消费税时的(1
  • 智能财税证书含金量如何
  • 安置房公摊面积多少属于正常范围
  • 重庆市九龙坡税务局行政服务中心电话
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

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

    友情链接: 武汉网站建设