Unity中一些为自己的记录(为自己)

You can also put your variants in a preset in the Project -> Graphics Settings on the bottom. That might help a bit

Try this:

1) Edit->Project Settings->Graphics->Shader Stripping->Instancing Variants->Strip All
2) Edit->Project Settings->Graphics->Shader Preloading->Save to asset...
3) Edit->Project Settings->Graphics->Shader Preloading->Preloaded Shaders->Assign saved shader variants asset
4) Check whether shader variants number changes between scenes, save multiple shader variant assets and assign when that's the case.
5) Make sure unless specifically required by your project. You make sure the bool for 'Enable GPU Instancing' is not ticked in your shaders (default is not ticked. You would have specifically ticked them more than likely).

It will compile slowly once I believe. Once that singular compile is done it won't need to re-compile for those options.

///

All tests were done on an intel core2duo 3ghz imac with no rendering, just physics.
Static colliders seem to have such a minimal impact on performance, Upto 60,000 and beyond of all different colliders were causing no noticable effect on the frame time (<3ms)
So I tried testing dynamic colliders instead, much more challenging.
Remember this is just physics, your renderer would bottleneck way before reaching 2500 individual objects.

Dynamic Tests:
500 Colliders
Capsule 2.1ms
Box 2.6ms
Sphere 2ms

1000 Colliders
Capsule 5.6ms
Box 5.8ms
Sphere 2.9ms

1500 Colliders
Capsule 16.1ms
Box 20.5ms
Sphere 4.8ms

2500 Colliders
Capsule 453-481ms
Box 490-520ms
Sphere 190-233ms

So there you have it, across the board capsule actually beats box but not by a huge amount, and sphere obviously kicks everyones ass.

* sphere collider -> 1 Vector
* capsule collider -> 2 sphere colliders + their distance vector
* Box collider -> no clue how it's done ;

//
SetUv第一个参数是索引。与TEXCOORD后面的数字对应。
每个顶点对应几个List<Vector4> ,几个对应结构体里的TEXCOORD数字

///

Unity的函数调用顺序

//关闭unity

#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#else 
            Application.Quit();
            System.Diagnostics.Process.GetCurrentProcess().Kill();
#endif

 

1、问题: 从3dsMax导出fbx给Unity用,总是会丢失贴图。尽管Unity导入fbx时会自动导入材质球,但是贴图文件都会变成空的,要重新一个一个贴图填进去,真是太浪费时间了

解决方案: 3dsMax中模型和贴图采用统一命名,贴图文件拷贝到Unity项目中,然后再导入fbx,就会为自动创建的材质找到对应贴图了。

2、通过脚本修改shader中uniform的值

  1. //shader的写法  
  2. Properties {  
  3.     ...  
  4.     disHeight ("threshold distance", Float) = 3  
  5. }  
  6.    
  7. SubShader {  
  8.     Pass {  
  9.         CGPROGRAM  
  10.         #pragma vertex vert    
  11.         #pragma fragment frag   
  12.         ...  
  13.         uniform float disHeight;  
  14.         ...   
  15. // ===================================  
  16. // 修改shader中的disHeight的值  
  17. gameObject.renderer.sharedMaterial.SetFloat("disHeight", height); 

3、使得脚本能够在editor中实时反映:在脚本前加上:[ExecuteInEditMode],。Inspector中右键[ContextMenu("名字")]

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

 

 

4、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中。
 

5、NGUI中设置自定义的Shader,并改变properties的值。

使用UITexture,可以设置自定义的Material。需要注意的是,改变properties的值,需要使用UITexture中的drawCall的dynamicMaterial,UITexture tex=....;  tex.drawCall.dynamicMaterial.SetFloat("_percent", du/DU);  

6、RenderTexture的全屏效果

cs端:
 

[csharp]

  1. MeshFilter mesh = quard.GetComponent<MeshFilter> ();  
  2. // 创建和摄像机相关的renderTexture  
  3. RenderTexture rTex = new RenderTexture ((int)cam.pixelWidth, (int)cam.pixelHeight, 16);  
  4. cam.targetTexture = rTex;  
  5. mesh.renderer.material.mainTexture = rTex;  
MeshFilter mesh = quard.GetComponent<MeshFilter> ();
// 创建和摄像机相关的renderTexture
RenderTexture rTex = new RenderTexture ((int)cam.pixelWidth, (int)cam.pixelHeight, 16);
cam.targetTexture = rTex;
mesh.renderer.material.mainTexture = rTex;

shader端:

 

[csharp]

  1. #include "UnityCG.cginc"             
  2. sampler2D _MainTex;  
  3. sampler2D _NoiseTex;  
  4.       
  5. struct v2f {      
  6.     half4 pos:SV_POSITION;      
  7.     half2 uv : TEXCOORD0;   
  8.     float4 srcPos: TEXCOORD1;    
  9. };    
  10.   
  11. v2f vert(appdata_full v) {    
  12.     v2f o;    
  13.     o.pos = mul (UNITY_MATRIX_MVP, v.vertex);    
  14.     o.uv = v.texcoord.xy;  
  15.     o.srcPos = ComputeScreenPos(o.pos);  
  16.     return o;    
  17. }    
  18.   
  19. fixed4 frag(v2f i) : COLOR0 {  
  20.     float tmp = saturate(1-(length(i.uv-float2(0.5,0.5)))*2)*0.04;            
  21.     float2 wcoord = (i.srcPos.xy/i.srcPos.w) + tex2D(_NoiseTex, i.uv) * tmp - tmp/2;  
  22.     return tex2D(_MainTex, wcoord);  
  23. }    
#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.04;        	
	float2 wcoord = (i.srcPos.xy/i.srcPos.w) + tex2D(_NoiseTex, i.uv) * tmp - tmp/2;
    return tex2D(_MainTex, wcoord);
}  
使用RenderTexture制作屏幕特效:
 
  1. [ExecuteInEditMode]  
  2. public class MyScreenEffect : MonoBehaviour {  
  3.     ...  
  4.     void OnRenderImage(RenderTexture source, RenderTexture dest) {  
  5.         Graphics.Blit(source, dest, material);  
  6.     }  
  7. }  
[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的架构请参考:http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter30.html
7、 浮点数相等的判断(由于浮点数有误差, 所以判断的时候最好不要用等号,尤其是计算出来的结果)
if (Mathf.Approximately(1.0, 10.0/10.0))  

print ("same");  



Unity3D 模拟鼠标单击/双击

using UnityEngine;
using System.Collections;

public class MouseResponseManager
{
	public static void Register(GameObject objectItem, Action clickCallback, Action doubleCallback)
	{
		if(objectItem == null)
		{
			objectItem = new GameObject();
			objectItem.name = "MouseResponseItem";
		}
		MouseResponseItem mouseResponseItem = objectItem.AddComponent<MouseResponseItem> ();
		mouseResponseItem.Init (clickCallback, doubleCallback);
	}
}
public class MouseResponseItem : MonoBehaviour
{
	private bool mouseDownStatus;
	private int mouseDownCount;
	private float lastTime;
	private float currentTime;

	private Action clickCallback;
	private Action doubleCallback;

	public void Init(Action clickCallback, Action doubleCallback)
	{
		this.clickCallback = clickCallback;
		this.doubleCallback = doubleCallback;
	}
	
	void Update()
	{
		if(Input.GetMouseButtonDown(0))
		{
			if(!this.mouseDownStatus)
			{
				this.mouseDownStatus = true;
				//Debug.Log("Click !");
				if(this.clickCallback != null) this.clickCallback();

				// 如果按住数量为 0
				if(this.mouseDownCount == 0)
				{
					// 记录最后时间
					this.lastTime = Time.realtimeSinceStartup;
				}
				this.mouseDownCount ++;
			}
		}
		
		if(Input.GetMouseButtonUp(0))
		{
			//Debug.Log("Up !");
			this.mouseDownStatus = false;
		}
		
		if(this.mouseDownStatus)
		{
			//Debug.Log("Hold !");
			if(this.mouseDownCount >= 2)
			{
				this.currentTime = Time.realtimeSinceStartup;
				if(this.currentTime - this.lastTime < 0.3f)
				{
					this.lastTime = this.currentTime;
					this.mouseDownCount = 0;
					//Debug.Log("Double Click");
					if(this.doubleCallback != null) this.doubleCallback();
				}
				else
				{
					// 记录最后时间
					this.lastTime = Time.realtimeSinceStartup;
					this.mouseDownCount = 1;
				}
			}
		}
	}
}
using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour 
{
	void Start()
	{
		MouseResponseManager.Register(null, ()=>
		{
			Debug.Log("click");
		}, ()=>{
			Debug.Log("double click");
		});
	}

	void OnGUI ()
	{
		GUI.Label(new Rect(15, 15,300, 100), "在舞台上单击/双击查看输出!");
	}

}



<color=yellow> </color>

 

<color=#CC8200FF></color>

 

修改windows窗口的标题名称,就是修改下图的东西:

https://img2018.cnblogs.com/blog/1227207/201810/1227207-20181019145543583-1998134318.png

 

 第一种:

using UnityEngine;

using System;

using System.Runtime.InteropServices;

public class SetWindowText : MonoBehaviour

{

    #region WIN32API

    delegate bool EnumWindowsCallBack(IntPtr hwnd, IntPtr lParam);

    [DllImport("user32", CharSet = CharSet.Unicode)]

    static extern bool SetWindowTextW(IntPtr hwnd, string title);

    [DllImport("user32")]

    static extern int EnumWindows(EnumWindowsCallBack lpEnumFunc, IntPtr lParam);

    [DllImport("user32")]

    static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref IntPtr lpdwProcessId);

    #endregion

    IntPtr myWindowHandle;

    public void Start()

    {

        IntPtr handle = (IntPtr)System.Diagnostics.Process.GetCurrentProcess().Id;  //获取进程ID

        EnumWindows(new EnumWindowsCallBack(EnumWindCallback), handle);     //枚举查找本窗口

        SetWindowTextW(myWindowHandle, "测试代码"); //设置窗口标题

    }

 

    bool EnumWindCallback(IntPtr hwnd, IntPtr lParam)

    {

        IntPtr pid = IntPtr.Zero;

        GetWindowThreadProcessId(hwnd, ref pid);

        if (pid == lParam)  //判断当前窗口是否属于本进程

        {

            myWindowHandle = hwnd;

            return false;

        }

        return true;

    }

}

第二种:

using System;

using System.Collections;

using System.Collections.Generic;

using System.Runtime.InteropServices;

using System.Text;

using UnityEngine;

 

public class NewBehaviourScript : MonoBehaviour {

 

    //Import the following.

    [DllImport("user32.dll", EntryPoint = "SetWindowTextW", CharSet = CharSet.Unicode)]

    public static extern bool SetWindowTextW(System.IntPtr hwnd, System.String lpString);

    [DllImport("user32.dll", EntryPoint = "FindWindow")]

    public static extern System.IntPtr FindWindow(System.String className, System.String windowName);

 

    public void Change()

    {

        //Get the window handle.

        var windowPtr = FindWindow(null, "WindowTitleChange");//打包时的ProductName,找到名字是WindowTitleChange的窗口

     //Set the title text using the window handle.
     SetWindowTextW(windowPtr, "测试代码");
    }
}

 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值