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

카테고리

분류 전체보기 (2737)
Unity3D (817)
Script (91)
Extensions (14)
Effect (3)
NGUI (77)
UGUI (8)
Physics (2)
Shader (36)
Math (1)
Design Pattern (2)
Xml (1)
Tips (200)
Link (22)
World (1)
AssetBundle (25)
Mecanim (2)
Plugins (70)
Trouble Shooting (68)
Encrypt (7)
LightMap (4)
Shadow (4)
Editor (8)
Crash Report (3)
Utility (9)
UnityVS (2)
Facebook SDK (2)
iTween (3)
Font (11)
Ad (14)
Photon (2)
IAP (1)
Google (8)
Android (45)
iOS (41)
Programming (474)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (58)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (53)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
04-25 00:00
Hey guys,

Just wanted to post a snippet in case it turns out to be helpful for anyone using an alternate localization solution with NGUI.

I'm currently using Smart Localization which can be found here: http://forum.unity3d.com/threads/173837-RELEASED-Smart-Localization-for-Unity3D

It's really good, it's free and has some neat features such as Microsoft Translate integration.

In order to use it with NGUI, simply type your string key into the label field and drag this script on.

Cheers!

Code (csharp):
  1.  
  2. using UnityEngine;
  3. using System.Collections;
  4. using System.Globalization;
  5.  
  6. [RequireComponent(typeof(UIWidget))]
  7. [AddComponentMenu("NGUI/UI/LocalizeWidget")]
  8. public class LocalizeWidget : MonoBehaviour
  9. {
  10.     // No public variables, we'll get the key from the widget field
  11.     private string key;
  12.     private string mLanguage;
  13.     private LanguageManager loc;
  14.  
  15.     // Localize the widget on start.
  16.     private void Start()
  17.     {
  18.         // Reference the language manager
  19.         loc = LanguageManager.Instance;
  20.        
  21.         // Hook up a delegate to run the localize script whenever a language was changed
  22.         loc.OnChangeLanguage += new ChangeLanguageEventHandler(Localize);
  23.        
  24.         // Initial localize run
  25.         Localize();
  26.     }
  27.    
  28.     // Incase the script didn't get the message from being inactive
  29.     private void OnEnable()
  30.     {
  31.         if(mLanguage != loc.language)
  32.             Localize();
  33.     }
  34.    
  35.     // Force-localize the widget.
  36.     private void Localize(LanguageManager thisLanguage=null)
  37.     {
  38.         UIWidget w = GetComponent<UIWidget>();
  39.         UILabel lbl = w as UILabel;
  40.         UISprite sp = w as UISprite;
  41.  
  42.         // If no localization key has been specified, use the label's text as the key
  43.         if (lbl != null)
  44.             key = lbl.text;
  45.        
  46.         string val = loc.GetTextValue(key);
  47.        
  48.         if(string.IsNullOrEmpty(val))
  49.             val = "Missing String";
  50.  
  51.         if (lbl != null)
  52.         {
  53.             // If this is a label used by input, we should localize its default value instead
  54.             UIInput input = NGUITools.FindInParents<UIInput>(lbl.gameObject);
  55.            
  56.             if (input != null  input.label == lbl)
  57.                 input.defaultText = val;
  58.             else
  59.                 lbl.text = val;
  60.         }
  61.         else if (sp != null)
  62.         {
  63.             sp.spriteName = val;
  64.             sp.MakePixelPerfect();
  65.         }
  66.        
  67.         // Set this widget's current language
  68.         mLanguage = loc.language;
  69.     }
  70. }
  71.  
 



출처 : http://forum.unity3d.com/threads/smart-localization-with-ngui.189253/


참조 : http://forum.unity3d.com/threads/released-smart-localization-for-unity3d.173837/

반응형
Posted by blueasa
, |



소스 주소 : https://github.com/totuworld/unity/



출처 : https://www.youtube.com/watch?v=G9AdSd88BFg


반응형
Posted by blueasa
, |

Momentum And Spring 


옵션을 주면.


양끝.


1~10번까지의 리스트가 있다면.


1번에서  리스트에 없는 0번위치까지 드래그가 되서 다시 1번으로 스프링되서 돌아오는 방식이다.(10번도 마찬가지 없는 11번으로 갔다가 다시 원래 10번으로 돌아옴)


Momentum 


옵션은.


그냥 정확히 끝에 1번이나 10번에서 멈춰서 양끝으로 더이상 드래그가 되질 않는 방식이다.




이 두개를 합쳐서 


Momentum And Spring 


옵션을 주고.


한쪽방향은 더이상 못움직이게.   한쪽방향은 스프링처럼 돌아오게 하려면.



UIScrollView - 클래스에서.


public bool m_BottomStop = false;
public bool m_TopStop = false;

변수 선언.

public void Drag () 의 

Vector3 constraint = mPanel.CalculateConstrainOffset(bounds.min, bounds.max);

if (constraint.magnitude > 1f)
{
    MoveAbsolute(offset * 0.5f);
mMomentum *= 0.5f;

}

이부분에.


if (constraint.magnitude > 1f)
{
MoveAbsolute(offset * 0.5f);
mMomentum *= 0.5f;

       //StopOption.
       if (m_BottomStop == true)
       {
             if (offset.y > 0)
               RestrictWithinBounds(true, canMoveHorizontally, canMoveVertically);
        }
        if (m_TopStop == true)
        {
              if (offset.y < 0)
                 RestrictWithinBounds(true, canMoveHorizontally, canMoveVertically);
         }
}

이렇게 적어주고

m_BottomStop 과 m_TopStop   에 True 값을 넣어줘서. 값을 셋팅해서 사용하면된다.


왼쪽 오른쪽도 만들고싶다면.

offset.x 를 활용하면 된다.



[출처] http://hanamoni.tistory.com/25

반응형
Posted by blueasa
, |

[원본 링크]

http://kheldon.tistory.com/2



올려진 파일은 공유해주신 위 원본링크의 소스를 개조해서 사용중입니다.(공유 감사합니다.)


[개조파일]

CUIListView.cs




[추가사항]

- SetFocusOnCenter 추가.

- WidgetBound 대신 BoxCollier를 ItemSize로 사용.

- Vertical에서 아이템이 아래로 붙는 문제 수정(위로 붙게..)


[추가사항] 2018-07-27

- ScrollBar 터치 로직 추가


반응형
Posted by blueasa
, |

프로젝트를 진행하다보면 NGUI의 label만으로는 표현이 뭔가 아쉬운 경우가 있다. 특히 게임 캐릭터나 유닛이 데미지를 받는다거나, 스코어를 보여준다거나 하는 상황에서 사이즈가 큰 폰트를 써야 할 경우가 많은데, 이럴 경우 기본 폰트의 크기가 작아 폰트가 지저분하게 보인다거나 게임 자체가 뭔가 허접(?)하게 보일 확률이 높다.

"0부터 9까지의 숫자 부분만 따로 떼어 특별한 이미지로 만든 후에 이것을 label로 쓸 수 있다면..?"

이런 생각으로, 데미지 폰트를 만드는 방법을 검색해 보았으나... BMFont를 이용한 폰트를 만드는 방법은 여기저기 블로그 등에 널려(...) 있는데 비해, 이미지로 구성된 숫자 폰트를 만드는 방법은 의외로 찾아보기 어려웠다. 약간의 삽질 끝에 숫자 폰트를 만드는 방법을 확실히 알게 되어 공유해 보겠다. 

준비물
Unity, NGUI, BMFont, 폰트로 만들 0부터 9까지의 이미지

참고로 여기서 사용한 각 툴의 버전은 다음과 같다.
Unity3D: 4.1.5
NGUI: 2.6.3
BMFont: 1.13

1. BMFont를 띄우고 0부터 9까지 폰트로 만들 숫자를 선택한다.


일반적인 BMFont를 만드는 과정과 거의 비슷한데, 폰트 중에 숫자 부분만을 선택(클릭)한다는 점이 다르다. (보통 인터넷에 돌아다니는 KS1001.txt 파일을 import하는 과정...)
숫자를 클릭하면 어두운 회색 박스가 약간 밝은 회색 박스로 변한다. 이런 식으로 0부터 9까지 선택을 한다.

2. Image Manager를 띄운다.


일반 폰트를 만들 때는 존재조차 있는지 몰랐던, Image Manager를 띄운다.

3. Import Image


Image Manager를 띄우면 달랑 메뉴 하나에 빈 창만 보이는데, 메뉴의 Image => Import image를 클릭한다.

4. Id 입력


파일을 선택하는 창이 뜨는데, 준비해둔 숫자 폰트 중 0번 이미지를 선택하자. 그러면 위와 같은 Icon Image 창이 뜬다.
여기서 주의할 점은 Id 부분인데, 0번 이미지의 Id를 48로 변경하고 Ok를 눌러주자.
나머지 1번부터 9번까지는 0번 이미지부터 순서대로 Id값을 1씩 늘려나가면 된다. 이렇게 하면 9번 이미지는 Id가 57번이 된다.


5. 설정 확인


0번부터 9번 이미지를 모두 Import했다면 위와 같은 화면을 볼 수 있을 것이다.
0부터 9까지의 문자 박스에 하늘색 점이 표시되어 있고, 밝은 회색 박스로 변해 있다는 것을 알 수 있다. 만약 자신이 작업한 결과물이 위의 스샷과 다르다면 지금까지의 작업 과정을 다시 한 번 차근차근 확인해 보자.


6. Export Options


이제 Export Options를 설정해야 한다. BMFont의 Options => Export Options를 클릭하여 옵션 창을 띄우자.
확인할 사항은 두 가지이다. 첫 번째는 Bit depth인데 32비트로 바꾸면 된다. 만약 8비트 상태 그대로 둔다면 원래의 색상이 아니라 희멀건 폰트를 보게 될 것이다. 두 번째는 Textures인데, 유니티 프로젝트에서는 대부분 png 이미지를 사용하므로, png로 바꾸면 된다.
Save bitmap font as...를 누르면 저장할 이름을 결정하는 창이 뜬다.
여기서는 DamageFont라고 정해보았다.


[참고] 이후의 과정은 일반적인 BMFont를 만드는 과정과 같다.

7. fnt를 txt로 변경


저장하면 fnt와 png 파일이 생긴다. 이 중 fnt 파일의 확장자를 fnt에서 txt로 바꾼다.


8. txt와 png를 유니티의 프로젝트로 드래그&드롭


앞의 과정에서 만든 txt와 png를 유니티의 프로젝트에 드래그&드롭한다.
이제 NGUI의 Font Maker를 열어 폰트를 만들면 되는데, 유니티 메뉴 => NGUI => Open the Font Maker를 클릭한다.


9. Font 아틀라스 만들기


지금까지의 과정을 정상적으로 진행했다면 위와 같은 모습을 볼 수 있다. 앞의 과정에서 프로젝트에 포함시켰던 txt 파일을 Font Data로 드래그하고, png 파일은 Texture로 드래그한다.
Font Name을 입력하고 Create 버튼을 누르면 프로젝트 폴더에 아틀라스와 마테리얼이 생성된다.


10. 최종 테스트


NGUI의 Widget Tool을 띄운 후, 조금 전 만든 DamageFont 아틀라스를 Font로 선택한다. Label을 만든 후 정상적으로 폰트가 출력되는지 확인하자. 지금까지의 과정을 차근차근 따라했다면 위의 스샷처럼 Scene 화면에서 데미지 폰트로 된 Label을 확인할 수 있을 것이다.


출처 : http://lianes.tistory.com/49

반응형
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
, |


링크 : 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
, |

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
, |