블로그 이미지
Every unexpected event is a path to learning for you. blueasa

카테고리

분류 전체보기 (2849)
Unity3D (893)
Programming (479)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (189)
협업 (64)
3DS Max (3)
Game (12)
Utility (141)
Etc (99)
Link (34)
Portfolio (19)
Subject (90)
iOS,OSX (52)
Android (16)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (19)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday

유니티로 개발을 하다보면 스크립트에서 public으로 빼놓은 것을 

EditMode(작업모드)에서 바로 적용된 것을 보고 싶을때가 있습니다.

처음에 유니티를 하게되면 항상 ▶버튼을 눌러 실행을 한 후 확인하게 됩니다.


물론 ▶버튼을 눌러서 확인을 해야 하는 경우도 있지만 가볍게 변경된 것을 스크립트를 통해 바로 확인하고 싶을 때 사용하면 좋을 것 입니다.


[ExecuteInEditMode] 를 사용하여 바로 변경되도록 할 수 있는데요.

이 키워드를 스크립트에서 class위에 배치를 하면 Update부분에 적용한 것을 EditMode에서 바로 확인 하실 수 있습니다.


/* 예제 */

/*******************************************************************/

[ExecuteInEditMode]

public class UIRoot : MonoBehaviour

{

void Update()

{

//EditMode이든 실행되는 화면이든 변경되었으면 하는 부분 처리

}

}

/*******************************************************************/ 






위에 두 그림 처럼 Manual Height 의 값을 조정하면 Transform 부분에 Scale 부분에 값이 변하는 것을 확인 하실 수 있을껍니다.

위에 두 그림은 실행모드가 아닌 EditMode임을 말씀 드립니다.




출처 : http://jhc777.tistory.com/65




The functions are not called constantly like they are in play mode.
Update is only called when something in the scene changed.
OnGUI is called when the Game View recieves an Event.

OnRenderObject and the other rendering callback functions are called on every repaint of the Scene View or Game View.


참조 : http://docs.unity3d.com/ScriptReference/ExecuteInEditMode.html

반응형
Posted by blueasa
, |
NGUI가 기본적으로 Sprite의 회색처리와 Bright처리를 지원하지 않아서
그동안 회색 처리된 이미지와 Bright처리된 이미지를 별도로 사용하다가,
도저히 노가다와 용량문제로 안되겠어서 구글링의 도움으로 여러 글을 참고로 만들어봤습니다.
NGUI스크립트를 일부 수정하셔야합니다. 
 
대략 다음 순서입니다.
스텝1. 새로운 쉐이더를 추가합니다.
스텝2. 만들어진 Atlas의 Material의 쉐이더를 추가한 쉐이더로 바꿉니다.
스텝3. UIAtlas의 코드를 수정합니다.
스텝4. UISprite의 코드를 수정합니다.
 
스텝1. 새로운 쉐이더 추가
NGUI/Resources/Shaders에 적당한 이름으로 저장합니다.
001Shader "Unlit/Transparent Colored (Gray)"
002{
003    Properties
004    {
005        _MainTex ("Base (RGB), Alpha (A)", 2D) = "black" {}
006        _EffectAmount ("Effect Amount", Range (0, 1)) = 0.0
007        _Intensity ("Intencity", float) = 1.0
008    }
009     
010    SubShader
011    {
012        LOD 100
013 
014        Tags
015        {
016            "Queue" "Transparent"
017            "IgnoreProjector" "True"
018            "RenderType" "Transparent"
019        }
020         
021        Cull Off
022        Lighting Off
023        ZWrite Off
024        Fog { Mode Off }
025        Offset -1, -1
026        Blend SrcAlpha OneMinusSrcAlpha
027 
028        Pass
029        {
030            CGPROGRAM
031                #pragma vertex vert
032                #pragma fragment frag
033                 
034                #include "UnityCG.cginc"
035     
036                struct appdata_t
037                {
038                    float4 vertex : POSITION;
039                    float2 texcoord : TEXCOORD0;
040                    fixed4 color : COLOR;
041                };
042     
043                struct v2f
044                {
045                    float4 vertex : SV_POSITION;
046                    half2 texcoord : TEXCOORD0;
047                    fixed4 color : COLOR;
048                };
049     
050                sampler2D _MainTex;
051                float4 _MainTex_ST;
052                fixed _EffectAmount;
053                half _Intensity;
054 
055                v2f vert (appdata_t v)
056                {
057                    v2f o;
058                    o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
059                    o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
060                    o.color = v.color;
061                    return o;
062                }
063                 
064                fixed4 frag (v2f i) : COLOR
065                {
066                    fixed4 col = tex2D(_MainTex, i.texcoord) * i.color;
067                    col.rgb = lerp(col.rgb, dot(col.rgb, float3(0.3, 0.59, 0.11)), _EffectAmount) * _Intensity;
068                    return col;
069                }
070            ENDCG
071        }
072    }
073 
074    SubShader
075    {
076        LOD 100
077 
078        Tags
079        {
080            "Queue" "Transparent"
081            "IgnoreProjector" "True"
082            "RenderType" "Transparent"
083        }
084         
085        Pass
086        {
087            Cull Off
088            Lighting Off
089            ZWrite Off
090            Fog { Mode Off }
091            Offset -1, -1
092            ColorMask RGB
093            AlphaTest Greater .01
094            Blend SrcAlpha OneMinusSrcAlpha
095            ColorMaterial AmbientAndDiffuse
096             
097            SetTexture [_MainTex]
098            {
099                Combine Texture * Primary
100            }
101        }
102    }
103}
 
스텝2. ​원하는 Atlas의 Material의 쉐이더를 방금 추가한 쉐이더로 바꿉니다.
 
스텝3. UIAtlas.cs의 코드를 수정합니다.
01[HideInInspector][SerializeField] Material material; // 이코드를 찾아서 밑에 코드를 추가합니다.
02[HideInInspector][SerializeField] Material materialGray;  // 추가
03[HideInInspector][SerializeField] Material materialBright; // 추가
04  
05  
06    // spriteMaterial을 수정합니다.
07    public Material spriteMaterial
08    {
09        get
10        {
11            return (mReplacement != null) ? mReplacement.spriteMaterial : material;
12        }
13        set
14        {
15            if (mReplacement != null)
16            {
17                mReplacement.spriteMaterial = value;
18            }
19            else
20            {
21                materialGray = null; // 추가됨
22                materialBright = null; // 추가됨
23                if (material == null)
24                {
25                    mPMA = 0;
26                    material = value;
27                }
28                else
29                {
30                    MarkAsChanged();
31                    mPMA = -1;
32                    material = value;
33                    MarkAsChanged();
34                }
35            }
36        }
37    }
38  
39    //추가
40    public Material spriteMaterialGrayscale {
41        get {
42            if (materialGray == null) {
43                materialGray = new Material(spriteMaterial);
44                materialGray.SetFloat("_EffectAmount", 1);
45            }
46            return materialGray;
47        }
48    }
49  
50    //추가
51    public Material spriteMaterialBright {
52        get {
53            if (materialBright == null) {
54                materialBright = new Material(spriteMaterial);
55                materialBright.SetFloat("_Intensity", 3);
56            }
57            return materialBright;
58        }
59    }
 
스텝4. UISprite.cs코드를 수정합니다.
01// 적당한 위치에 추가합니다.
02 [System.NonSerialized] bool isGray  = false; // 추가
03 [System.NonSerialized] bool isBright  = false; // 추가
04 
05 
06 // material getter를 수정합니다.
07 public override Material material {
08     get {
09         if (mAtlas == null) {
10             return null;
11         }
12         if (isGray) {
13             return mAtlas.spriteMaterialGrayscale;
14         }
15         if (isBright) {
16             return mAtlas.spriteMaterialBright;
17         }
18         return mAtlas.spriteMaterial;
19     }
20 }
21 
22// 추가합니다.
23 public void GrayScale(bool gray) {
24     isGray = gray;
25     if (panel != null) {
26         panel.RebuildAllDrawCalls();
27     }
28 }
29 
30// 추가합니다.
31 public void Bright(bool bright) {
32     isBright = bright;
33     if (panel != null) {
34         panel.RebuildAllDrawCalls();
35     }
36 }
 
여기까지 하셨으면 작업완료!
아래와 같이 회색처리 / Bright처리 가능합니다.
sprite.GrayScale(true);
sprite.Bright(true);NGUI가 기본적으로 Sprite의 회색처리와 Bright처리를 지원하지 않아서
그동안 회색 처리된 이미지와 Bright처리된 이미지를 별도로 사용하다가,
도저히 노가다와 용량문제로 안되겠어서 구글링의 도움으로 여러 글을 참고로 만들어봤습니다.
NGUI스크립트를 일부 수정하셔야합니다. 
 
대략 다음 순서입니다.
스텝1. 새로운 쉐이더를 추가합니다.
스텝2. 만들어진 Atlas의 Material의 쉐이더를 추가한 쉐이더로 바꿉니다.
스텝3. UIAtlas의 코드를 수정합니다.
스텝4. UISprite의 코드를 수정합니다.
 
스텝1. 새로운 쉐이더 추가
NGUI/Resources/Shaders에 적당한 이름으로 저장합니다.
001Shader "Unlit/Transparent Colored (Gray)"
002{
003    Properties
004    {
005        _MainTex ("Base (RGB), Alpha (A)", 2D) = "black" {}
006        _EffectAmount ("Effect Amount", Range (0, 1)) = 0.0
007        _Intensity ("Intencity", float) = 1.0
008    }
009     
010    SubShader
011    {
012        LOD 100
013 
014        Tags
015        {
016            "Queue" "Transparent"
017            "IgnoreProjector" "True"
018            "RenderType" "Transparent"
019        }
020         
021        Cull Off
022        Lighting Off
023        ZWrite Off
024        Fog { Mode Off }
025        Offset -1, -1
026        Blend SrcAlpha OneMinusSrcAlpha
027 
028        Pass
029        {
030            CGPROGRAM
031                #pragma vertex vert
032                #pragma fragment frag
033                 
034                #include "UnityCG.cginc"
035     
036                struct appdata_t
037                {
038                    float4 vertex : POSITION;
039                    float2 texcoord : TEXCOORD0;
040                    fixed4 color : COLOR;
041                };
042     
043                struct v2f
044                {
045                    float4 vertex : SV_POSITION;
046                    half2 texcoord : TEXCOORD0;
047                    fixed4 color : COLOR;
048                };
049     
050                sampler2D _MainTex;
051                float4 _MainTex_ST;
052                fixed _EffectAmount;
053                half _Intensity;
054 
055                v2f vert (appdata_t v)
056                {
057                    v2f o;
058                    o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
059                    o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
060                    o.color = v.color;
061                    return o;
062                }
063                 
064                fixed4 frag (v2f i) : COLOR
065                {
066                    fixed4 col = tex2D(_MainTex, i.texcoord) * i.color;
067                    col.rgb = lerp(col.rgb, dot(col.rgb, float3(0.3, 0.59, 0.11)), _EffectAmount) * _Intensity;
068                    return col;
069                }
070            ENDCG
071        }
072    }
073 
074    SubShader
075    {
076        LOD 100
077 
078        Tags
079        {
080            "Queue" "Transparent"
081            "IgnoreProjector" "True"
082            "RenderType" "Transparent"
083        }
084         
085        Pass
086        {
087            Cull Off
088            Lighting Off
089            ZWrite Off
090            Fog { Mode Off }
091            Offset -1, -1
092            ColorMask RGB
093            AlphaTest Greater .01
094            Blend SrcAlpha OneMinusSrcAlpha
095            ColorMaterial AmbientAndDiffuse
096             
097            SetTexture [_MainTex]
098            {
099                Combine Texture * Primary
100            }
101        }
102    }
103}
 
스텝2. ​원하는 Atlas의 Material의 쉐이더를 방금 추가한 쉐이더로 바꿉니다.
 
스텝3. UIAtlas.cs의 코드를 수정합니다.
01[HideInInspector][SerializeField] Material material; // 이코드를 찾아서 밑에 코드를 추가합니다.
02[HideInInspector][SerializeField] Material materialGray;  // 추가
03[HideInInspector][SerializeField] Material materialBright; // 추가
04  
05  
06    // spriteMaterial을 수정합니다.
07    public Material spriteMaterial
08    {
09        get
10        {
11            return (mReplacement != null) ? mReplacement.spriteMaterial : material;
12        }
13        set
14        {
15            if (mReplacement != null)
16            {
17                mReplacement.spriteMaterial = value;
18            }
19            else
20            {
21                materialGray = null; // 추가됨
22                materialBright = null; // 추가됨
23                if (material == null)
24                {
25                    mPMA = 0;
26                    material = value;
27                }
28                else
29                {
30                    MarkAsChanged();
31                    mPMA = -1;
32                    material = value;
33                    MarkAsChanged();
34                }
35            }
36        }
37    }
38  
39    //추가
40    public Material spriteMaterialGrayscale {
41        get {
42            if (materialGray == null) {
43                materialGray = new Material(spriteMaterial);
44                materialGray.SetFloat("_EffectAmount", 1);
45            }
46            return materialGray;
47        }
48    }
49  
50    //추가
51    public Material spriteMaterialBright {
52        get {
53            if (materialBright == null) {
54                materialBright = new Material(spriteMaterial);
55                materialBright.SetFloat("_Intensity", 3);
56            }
57            return materialBright;
58        }
59    }
 
스텝4. UISprite.cs코드를 수정합니다.
01// 적당한 위치에 추가합니다.
02 [System.NonSerialized] bool isGray  = false; // 추가
03 [System.NonSerialized] bool isBright  = false; // 추가
04 
05 
06 // material getter를 수정합니다.
07 public override Material material {
08     get {
09         if (mAtlas == null) {
10             return null;
11         }
12         if (isGray) {
13             return mAtlas.spriteMaterialGrayscale;
14         }
15         if (isBright) {
16             return mAtlas.spriteMaterialBright;
17         }
18         return mAtlas.spriteMaterial;
19     }
20 }
21 
22// 추가합니다.
23 public void GrayScale(bool gray) {
24     isGray = gray;
25     if (panel != null) {
26         panel.RebuildAllDrawCalls();
27     }
28 }
29 
30// 추가합니다.
31 public void Bright(bool bright) {
32     isBright = bright;
33     if (panel != null) {
34         panel.RebuildAllDrawCalls();
35     }
36 }
 
여기까지 하셨으면 작업완료!
아래와 같이 회색처리 / Bright처리 가능합니다.
sprite.GrayScale(true);
sprite.Bright(true);



출처 : http://devkorea.co.kr/bbs/board.php?bo_table=m03_lecture&wr_id=3561

반응형
Posted by blueasa
, |

NGUIDiscussion group: 333417608

Demand

Click on the monster portrait, portrait. (restrictions: highlight value only)

Method

Copy the Unlit - Transparent Colored.shader, modify(Finally, a complete shader)



Shader "Unlit/Transparent Colored" 


Instead of


Shader "Unlit/Transparent Colored (Bright)"


2,


Properties
	{
		_MainTex ("Base (RGB), Alpha (A)", 2D) = "black" {}
	}


Instead of


Properties
	{
		_MainTex ("Base (RGB), Alpha (A)", 2D) = "black" {}
		_Bright("Brightness", Float) = 2
	}

3, 

sampler2D _MainTex;
float4 _MainTex_ST;


Instead of


sampler2D _MainTex;
float4 _MainTex_ST;
float _Bright;

4, 

fixed4 frag (v2f i) : COLOR
{
	fixed4 col = tex2D(_MainTex, i.texcoord) * i.color;
	return col;
}


Instead of


fixed4 frag (v2f i) : COLOR
{
	fixed4 col = tex2D(_MainTex, i.texcoord) * i.color;
	col.rgb = _Bright * col.rgb;
	return col;
}

5, Save the name for the Unlit - Transparent Colored (Bright).shader 

Create a new Atlas


ReplicationAtlas and Material, pictured above is Wooden Atlas 1 (two is respectively Atlas and Material)

Material Atlas Wooden Atlas 1Designated asWooden Atlas 1

Revise the new Material


Increasing the brightness


Can be modified Brightness (Note: the modified window may not immediately display effect, need to refresh force corresponding to the Panel)



Application

The code which, when using the corresponding sprite atlas specified for the new atlas.


Effect


On the left is the highlighted icon. On the right is the ashing.


With complete Shader

Highlight

Shader "Unlit/Transparent Colored (Bright)"
{
	Properties
	{
		_MainTex ("Base (RGB), Alpha (A)", 2D) = "black" {}
		_Bright("Brightness", Float) = 2
	}
	
	SubShader
	{
		LOD 100

		Tags
		{
			"Queue" = "Transparent"
			"IgnoreProjector" = "True"
			"RenderType" = "Transparent"
		}
		
		Cull Off
		Lighting Off
		ZWrite Off
		Fog { Mode Off }
		Offset -1, -1
		Blend SrcAlpha OneMinusSrcAlpha

		Pass
		{
			CGPROGRAM
				#pragma vertex vert
				#pragma fragment frag
				
				#include "UnityCG.cginc"
	
				struct appdata_t
				{
					float4 vertex : POSITION;
					float2 texcoord : TEXCOORD0;
					fixed4 color : COLOR;
				};
	
				struct v2f
				{
					float4 vertex : SV_POSITION;
					half2 texcoord : TEXCOORD0;
					fixed4 color : COLOR;
				};
	
				sampler2D _MainTex;
				float4 _MainTex_ST;
				float _Bright;
				
				v2f vert (appdata_t v)
				{
					v2f o;
					o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
					o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
					o.color = v.color;
					return o;
				}
				
				fixed4 frag (v2f i) : COLOR
				{
					fixed4 col = tex2D(_MainTex, i.texcoord) * i.color;
					col.rgb = _Bright * col.rgb;
					return col;
				}
			ENDCG
		}
	}

	SubShader
	{
		LOD 100

		Tags
		{
			"Queue" = "Transparent"
			"IgnoreProjector" = "True"
			"RenderType" = "Transparent"
		}
		
		Pass
		{
			Cull Off
			Lighting Off
			ZWrite Off
			Fog { Mode Off }
			Offset -1, -1
			ColorMask RGB
			AlphaTest Greater .01
			Blend SrcAlpha OneMinusSrcAlpha
			ColorMaterial AmbientAndDiffuse
			
			SetTexture [_MainTex]
			{
				Combine Texture * Primary
			}
		}
	}
}


Ashing


Shader "Unlit/Transparent Colored (Gray)"
{
	Properties
	{
		_MainTex ("Base (RGB), Alpha (A)", 2D) = "black" {}
	}
	
	SubShader
	{
		LOD 100

		Tags
		{
			"Queue" = "Transparent"
			"IgnoreProjector" = "True"
			"RenderType" = "Transparent"
		}
		
		Cull Off
		Lighting Off
		ZWrite Off
		Fog { Mode Off }
		Offset -1, -1
		Blend SrcAlpha OneMinusSrcAlpha

		Pass
		{
			CGPROGRAM
				#pragma vertex vert
				#pragma fragment frag
				
				#include "UnityCG.cginc"
	
				struct appdata_t
				{
					float4 vertex : POSITION;
					float2 texcoord : TEXCOORD0;
					fixed4 color : COLOR;
				};
	
				struct v2f
				{
					float4 vertex : SV_POSITION;
					half2 texcoord : TEXCOORD0;
					fixed4 color : COLOR;
				};
	
				sampler2D _MainTex;
				float4 _MainTex_ST;
				
				v2f vert (appdata_t v)
				{
					v2f o;
					o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
					o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
					o.color = v.color;
					return o;
				}
				
				fixed4 frag (v2f i) : COLOR
				{
					fixed4 col = tex2D(_MainTex, i.texcoord) * i.color;
					col.rgb = dot(col.rgb, fixed3(.222,.707,.071));
					return col;
				}
			ENDCG
		}
	}

	SubShader
	{
		LOD 100

		Tags
		{
			"Queue" = "Transparent"
			"IgnoreProjector" = "True"
			"RenderType" = "Transparent"
		}
		
		Pass
		{
			Cull Off
			Lighting Off
			ZWrite Off
			Fog { Mode Off }
			Offset -1, -1
			ColorMask RGB
			AlphaTest Greater .01
			Blend SrcAlpha OneMinusSrcAlpha
			ColorMaterial AmbientAndDiffuse
			
			SetTexture [_MainTex]
			{
				Combine Texture * Primary
			}
		}
	}
}

Posted by Louis at February 26, 2014 - 10:17 PM



출처 : http://www.programering.com/a/MzM5ATMwATY.html

반응형
Posted by blueasa
, |
UniLinq라고 일본분이 mono 3.10에서 Linq 부분을 발췌해서 만드신것 같습니다. 저도 테스트 중인데 아직 별 문제 없네요(order by 같은 부분) 관심있으신 분은 한번받아서 테스트 해보세요. 




[출처]

http://www.gamecodi.com/board/zboard.php?id=GAMECODI_Talkdev&page=1&sn1=&divpage=1&sn=off&ss=on&sc=on&select_arrange=headnum&desc=asc&no=3401

반응형
Posted by blueasa
, |


링크 : http://betrayrokeu.tistory.com/entry/NGUI-%EC%8A%A4%ED%81%AC%EB%A1%A4%EB%B7%B0-%EC%9E%AC%EC%82%AC%EC%9A%A9

반응형
Posted by blueasa
, |


링크 : http://blog.naver.com/blue9954/220393256568


참조 : http://blog.naver.com/blue9954/220391202268



반응형

'Unity3D > LightMap' 카테고리의 다른 글

[펌] Unity 5 lightmapped scene assetbundle problem  (0) 2017.04.19
LightMapSize 조절  (0) 2014.03.18
Unity Lightmapping Tips, Tricks and Thoughts  (0) 2014.03.18
Posted by blueasa
, |

A lot of people in the use of NGUI time, released to the device that the picture becomes fuzzy, below is a simple method to correct the problem.

This refers to the automatic generation of NGUI Atlas Texture.

The following:




1, Texture Type, Use Advanced to display all properties

2, Generate Mip Maps, UI don't need, so check out.

3, FilterMode, Select the Bilinear would be more clear

4, Max Size, Depends on your target platform, general control in 2048 words can be suitable for the majority of mobile platform

5, Format, Depending on the original mass of your picture, Automatic Truecolor is the best, but the picture is also the largest.



출처 : http://www.programering.com/a/MzM5ADNwATc.html

반응형
Posted by blueasa
, |

Unity3D v.3.5.5f3 Pro / iOS Pro (with 2D ToolKit) 기준.


1. 이미지 자체 최적화


png 등의 이미지를 import 하면 압축된 용량이 아닌 원래 용량으로 인입됨.

아이폰의 경우 pvrtc로 압축하여 용량 줄일 수 있음.


256 x 256 size 이미지 크기 비교

 - RGBA 32bit : 256 kb

 - RGBA 16bit : 128 kb

 - RGBA Compressed PVRTC4 : 32 kb

 - RGBA Compressed PVRTC2 : 16 kb


texture type 설정

 - GUI/HUD 용도로 사용하는 이미지는 GUI로 설정 (이미지 품질이 가장 좋음)

 - 그 외는 Texture 혹은 Advanced 선택

   - Advanced는 Texture 설정에서 사용자가 옵션 선택 가능

   - Advanced에서 "Generate Mip maps" 설정을 해제하면 용량을 줄일 수 있다. 

    (2D에선 불필요. 게임 화면과 카메라와의 거리를 가깝게 잡은 경우 화질 개선에도 도움이 됨)


이미지 비율 조정

 - Unity3d에서는 한 변의 길이가 2의 배수인 정사각형으로 이미지를 사용하게 됨. (2, 4, 8, 16 …)

 - 압축할 때 이를 2의 배수인 정사각형으로 늘려주므로 정사각형 안에 들어가도록 사용할 것.

   - 9 x 9 이미지는 16 x 16 으로 늘어나게 됨.

   - 툴을 통해 이미지 병합시 만약 8 x 16 처럼 비율이 맞지 않을 경우 동일하게 16 x 16으로 늘어나므로

     8 x 8 두장 혹은 다른 이미지를 더 합쳐 16 x 16으로 만드는 것이 용량면에서는 좋음 (성능과 반비례)

   - 실제 1024 x 1024 altas를 PVRTC4로 압축시 용량은 0.5 mb정도 (2048 x 2048 : 2mb)


2. 이미지 화질과의 상관관계


개별 이미지를 atlas로 합치는 것이 성능 면에서는 도움이 됨.

 - but atlas size가 커질 경우 화질이 떨어질 수 있음. (정확한 원인은 파악 못함)

 - 개인적인 관점에서 1024정도가 적당한 듯. (2048 이상일 경우 화질 저하 정도가 꽤 큼)

 - 4096 사이즈의 경우는 iphone에서 이미지가 보이지 않음

    - Edit / Graphic Emulation 설정을 No emulation으로 설정할 경우 보인다는 글이 있었으나 적용해도 보이지 않아 실패함.


3. 용량 & 성능


이미지를 import하고 이를 atlas로 병합하는 과정을 거칠 경우 원본 이미지가 프로젝트에 포함되어 있을 수 있음.

 - 실제 build시 unity에서 사용하지 않는 이미지는 포함시키지 않게 되어 있으나

   Asset 폴더 내에 Resource 폴더가 있을 경우 Resource 폴더 내의 모든 내용은 강제로 프로젝트에 포함됨. (동적 로딩용)

 - 원본 이미지를 별도로 압축하지 않은 경우 앱 용량이 매우 커질 수 있음. =_=


iOS build 시 설정

 - Target Device : iPhone / iPad보다 iPhone 혹은 iPad 단독으로 설정

 - Target Platform : armv6 < armv7 < armv6 & 7

 - Api Compatibility Level : .NET 2.0 Subset < .NET 2.0

 - Stripping Level : Use micro mscorlib < Strip ByteCode < Strip Assemblies < Disabled

 - Script Call Optimization : Fast but no Exceptions < Slow and Safe



출처 : http://neojsm.tistory.com/10

반응형
Posted by blueasa
, |

약 2~3 주 전 빌드를 하다 보니 apk 파일 용량이 50MB 가 넘어가는 상황이 벌어졌다....

(google 정책상 50 MB가 넘어가면 안된다고 한다 )

느낌표


당장 내일이 업데이트라 급한대로 부랴부랴 별로 티 가 나지 않는 아이콘 이미지들의 크기를 줄여서


빌드를 해서 간신히 50MB 이하로 줄이긴 했지만


앞으로 추가적인 콘텐츠에 의해 이미지 들이 추가 될 시에 같은 문제가 발생할거 같기에 


대처방안이 필요했다.


대부분의 리소스 파일들은 CDN 서버에서 다운 받아 사용하는 방식을 쓰고 있으니

제일 큰 용량을 차지하는 Atlas 파일들 또한 CDN 서버에서 다운 받아 로드 하는 방식으로 변경하면

될거 같기에 구글링을 시작 하였다. 


찾아 보니 의외로 간단 하였다


Unity Pro 에서는 assetbundle 파일을 만들기 및 로드하기가 된다고 한다 (Unity Basic 버전에서는 안된다고 한다 실제 테스트 는 해보진 않았다 ) 


1.스크립트 작성 (AssetBundle Create)



Atlas 가 있는 프로젝트 내부에 위와 같은 스크립트를 넣기만 하면 

유니티 상단의 메뉴 바에  Export 라는 항목이 생길것이다 



2. AssetBundle 생성하기 


그 다음은 프로젝트 뷰에 있는 아틀라스를 선택후 상단의 새로만든 Export메뉴를 눌러서

저장할 위치를 정하고 저장을 누르면 AssetBundle 이 생성된다

이때 중요한건 Atlas는 3가지로 구성되어 있따 GameObject(Prefab), Material, Texture 로 이루어져있는대

AssetBundle을 만드는건 GameObject만 선택한 상태로 만들면된다. 

또한 각각 GameObject , Material, Textture 의 이름은 달라야 한다 . 


예를들어 Atlas_Test_go, Atlas_Text_mat, Atlas_Test_tex, 이런식으로 이름을 다르게 해야 한다 이름이 같으면 잘안된다는대 이는 직접해보진 않고 처음부터 따로 이름을 바꾼뒤 어셋번들을 생성하였기에 이것은 궁금 하신분은 직접 해보도록..


또한 GameObject가 아닌 Material 이나, Texture로만 Assetbundle을 뽑아서 로드 하려고하면 실제 궁극적으로 필요한 Ngui의 UIAtlas 라는 객체가 없어서 필요한 Sprite에 Atlas를 세팅할수 없다.


GameObject 만 AssetBundle 을 생성하여도 AssetBundle 을 뽑는 함수의 옵션 때문인지 하위의 정보들도 같이 합쳐져서 만들어 지는 거 같다. 실제로 해당 파일을 로드할때 디버깅을 하면서 보니 로드된 목록에 Texture 와 Material이 포함되어 있었다.



3. Atlas 를 로드 해보자.





당연 하지만 위 소스 중에 _resourcepath 는 실제 AssetBundle 파일이 있는 장소여야 한다. 해당 경로에서 해당 확장자를 가진 ( 확장자를 .dp로 하였기에 해당 확장자를 긁어 모았다 ) 

읽어 들인뒤 로드하였다 이떄 ab.Load() 함수를 사용하였는대 AllLoad()를 사용하게 되면 해당 파일의 어떤 것들이 담겨져 있는지 보이는대 이를 디버깅으로 까보면 확실히 기억은 안나지만 5~6개의 파일들이 담겨져 있던걸로 기억한다.


하지만 우리가 필요한건 Atlas GameObject 이기에 typeof(GameObject)로 골라내어 로드한후 해당 Gameobjcet 의 UIAtlas  객체를 뽑아내어 Atlas 목록에 넣고 있다. 


4. Load  한 Atlas 적용하기.




이제 우리가 마지막으로 원하는건 로드한 Atlas 를 써먹는거다 .

위와 같은 간단한 소스를 만들어서 Sprite 에 넣어주면 해당 Sprite 가 Awake 될때 

에디터상의 세팅된 AtlasKind에 따라 자기 자신의 Atlas 를  세팅하고 Sprite 이미지 까지 

지정된 이름으로 세팅한다.



 - 잡소리


이러한 Atlas 를 외부에서 로드해서 사용하는 것들은 이미지들이 더 추가될 가능성이 낮고 

또한 실제 이런 이미지들을 사용하는 것들이 런타임 도중 동적으로 이미지가 바뀔 가능성이 

낮은 것들을 위주로 하였기에 ( 또한 아틀라스가 로딩 되기전에 보여지는 이미지가 아닌 것들 )

Awake 함수에서 한번 로드된 아틀라스 로 자기 자신의 아틀라스와 이미지를 세팅하고

끝내는 방식으로 하였다


당연히 아틀라스를 로드 하기전에 보여져야 되는 이미지들은 이런식으로 하면안된다

(로고라던지, 로딩 화면이라던지)


또한 이미지가 런타임 도중 계속 바뀌어야 하는 것들 인벤창의 아이템 이라 던지...

이런 것들은 이미지가 추가될 가능성도 높고 이미지들이 바뀌거나 세팅 되거나 하기전에 가장먼저

Atlas가 세팅되어야 하므로 ( 아틀라스가 세팅되기전의 해당 Sprite의 이미지를 바꾸거나 한다면...

Error가 나던가..? 아마 안나긴 할거다 하지만 아무런 이미지도 보이지 않을거다 ) 

신경써야 되는 부분이 더 생길거 같기도 하고 아이템아이콘 같은경우 사용하는 부분이 너무 많아 그런 여러곳을 전부다 찾아가며 테스트 해보기 귀찮아서 


간단하고 바뀔일 없고 이미지는 커서 용량을 많이 차지하는 것들 로 해당 작업을 하였다.


위의 소스들을 그대로 쓴다면 아마 안될거다(Export스크립트 제외 ) 

그러니 안되는건 레퍼런스를 참조해보도록.... 




출처 : http://chocotart.tistory.com/entry/NGUI-Atlas-Assetbundle-%EB%A7%8C%EB%93%A4%EA%B8%B0-%EB%B0%8F-%EB%A1%9C%EB%93%9C-%ED%95%98%EA%B8%B0

반응형
Posted by blueasa
, |

 

 

[기존 소스에 일부 코드 수정]

CUIListView.cs
0.03MB

 

 

스크롤뷰 아이템을 재사용 할 수 있게 해주는 스크립트 입니다.

인터넷에 이미 몇가지 있는 걸로 알지만, 제가 쓰고 있는 것도 공유해 봅니다.

 

사용법은 간단합니다.

스크립트에 멤버 변수로 CUIListView를 등록하면 다음과 같이 나옵니다. 

 

 

Item List - 스크롤뷰가 포함되어 있는 오브젝트.

Item - 리스트로 출력할 프리팹.

Add Row of Column - 0일 경우 View사이즈에 딱 맞게 아이템을 생성해줍니다. 이렇게 되면 아이템 재사용이 제대로 동작하지 않으니, 1이나 2로 지정합니다.

Item Padding - 아이템 사이의 간격입니다. 알아서 다 맞춰주기 때문에 Grid 사용하지 않아도 됩니다.

Scrollbar - 스크롤바가 있을경우 지정해줍시다.

그리고 UIPanel의 offset과 Center 좌표는 0으로 두는게 좋습니다. 패널 위치를 옮기려면 게임오브젝트의 좌표를 움직이는게 좋습니다.


using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CListViewTest : MonoBehaviour
{
    public CUIListView m_ListView;

    private List m_ItemList = new List();

    void Start ()
    {
        for(int i = 0; i < 500; ++i)
        {
            m_ItemList.Add(i);
        }

        m_ListView.OnUpdateItem = OnUpdateItem;
        m_ListView.OnGetItemCount = OnGetItemCount;

        m_ListView.Init();
    }

    public void OnUpdateItem(int index, GameObject go)
    {
        CListViewTestItem item = go.GetComponent<CListViewTestItem>();
        item.m_Label.text = index.ToString();
    }

    public int OnGetItemCount()
    {
        return m_ItemList.Count;
    }
}

public class CListViewTestItem : MonoBehaviour
{
    public UILabel m_Label;
}

 

코드는 위와같이 작성합니다. 

OnUpdateItem - 아이템이 갱신될 때 호출됩니다. 나머지 부분은 직접 구현하시면 됩니다. 

OnGetItemCount - 리스트의 전체 개수가 필요할 때 호출됩니다.

추가로 Refresh와 Reset, SetFocus 함수가 있는데 필요에 따라서 호출하여 쓰시면 될 것 같습니다.

 

미구현 기능 및 버그

- 스크롤 바를 클릭해서 뷰를 이동하는 기능. 이 기능을 쓸일이 없고 작업하기도 힘들어서 구현하지 않았습니다.

- 아이템이 한페이지 이상 삭제되었을 경우에 Refresh를 호출하면 뷰 이동이 안되는 버그. (이런 경우에는 Reset을 쓰는 걸 추천).

2015. 4. 15 업데이트

아이템이 리스트에 딱 맞게 설정되어 있을 경우에 스크롤이 되는 버그가 있어서 수정하였습니다.

 

2015. 5. 26 업데이트

아이템의 크기가 뷰사이즈 보다 작을 경우 드래그가 불가능 하도록 스크롤뷰를 disable 시키는 기능 추가.

SetFocus(0); 을 호출 할 경우 0번째 아이템이 화면 중앙에 위치하는 버그 수정.

 

출처 : http://kheldon.tistory.com/2

 

반응형
Posted by blueasa
, |