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

카테고리

분류 전체보기 (2738)
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 (475)
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
05-08 00:11

Useful stuff for NGUI

Unity3D/NGUI / 2018. 6. 7. 16:22

I've decided to create a sticky where I can bookmark topics that others may find useful. I'll keep adding stuff here (and you're welcome to reply to suggest other additions).



[출처] http://www.tasharen.com/forum/index.php?topic=776.msg34546#msg34546http://www.tasharen.com/forum/index.php?topic=776.msg34546#msg34546

반응형
Posted by blueasa
, |
초맨  2013.05.29 16:40  
자답입니다. 

NGUI 소스를 분석해 보니 직접적으로 이벤트를 발생시켜주지는 않는군요., 
대신 UIDraggablePanel 에서 드래그를 완료했을때 발생시켜 주는 이벤트(델리게이트로 구현)를 받아 
좌표 계산 후 상단끝에 도달했는지 하단끝에 도달했는지 판단할 수 있습니다. 

1. 델리게이트 등록 
dragPanel.onDragFinished = new UIDraggablePanel.OnDragFinished(OnDragFinished); 

2. 드래그완료 이벤트에서 좌표계산 후 영역판단. 
void OnDragFinished() 

Vector3 constraint = dragPanel.panel.CalculateConstrainOffset(dragPanel.bounds.min, dragPanel.bounds.max); 
if (constraint.y > 0) 

// 상단끝 

else if (constraint.y < 0) 

// 하단끝 

}




[출처] http://www.devkorea.co.kr/bbs/board.php?bo_table=m03_qna&wr_id=30574

반응형
Posted by blueasa
, |

GUI 최적화의 핵심은 정적인 UI 들과 동적인 UI 들을 나누는 것이다. 나누는 기준은 패널이다. 예를 들어 다음과 같은 하이어라키를 생각해볼 수 있다.




Panel1

정적인 UI들


Panel2

동적인 UI들




이렇게 하는 이유는 UI 가 갱신될 때마다 UI 가 속한 패널의 지오매트리가 재구성되기 때문이다. 재구성 작업에 많은 양의 가비지가 발생한다. 여기서 주의해야할 점은 위치 이동같은 기본 변환은 '갱신' 에 포함되지 않는다는 것이다. 지오매트리가 변해야 하는 작업들, 예를 들어 SetActive, UILabel 의 text 변경 등이 갱신에 포함된다.




패널의 UI 들중 하나라도 갱신이 되면 패널의 모든 UI 들에 대한 지오매트리 재구성 작업이 수행된다. 따라서 제일 최악의 시나리오는 패널을 루트에 단 하나 만들어두는 것이다. 이러면 UI 의 변경은 곧 씬의 모든 UI 들의 갱신이라는 결과로 작용한다.




동적인 UI 들 역시 하나의 패널로 몰아넣는건 같은 이유로 피해야 한다. 그렇다고 해서 패널의 개수를 너무 많이 늘려서는 안되는데, 패널 단위로 드로우콜이 분리되기 때문에 렌더링 성능은 낮아진다. 따라서 성능 측정을 결과로 패널의 개수를 조절할 필요가 있다.




출처: http://cacodemon.tistory.com/entry/NGUI-최적화의-핵심 [카코데몬의 잡동사니]

반응형
Posted by blueasa
, |

I Just Modified UI Label Code 

From
   public string text
   {
      get
      {
         return mText;
      }
      set
      {
         if (string.IsNullOrEmpty(value))
         {
            if (!string.IsNullOrEmpty(mText))
               mText = "";
            hasChanged = true;
         }
         else if (mText != value)
         {
            mText = value;   <=== Here
            hasChanged = true;
         }
      }
   }


To
   public string text
   {
      get
      {
         return mText;
      }
      set
      {
         if (string.IsNullOrEmpty(value))
         {
            if (!string.IsNullOrEmpty(mText))
               mText = "";
            hasChanged = true;
         }
         else if (mText != value)
         {
            mText = value.Replace("\\n", "\n");  <== Here
            hasChanged = true;
         }
      }
   }


I Didn't consider performance :)




[출처] http://www.tasharen.com/forum/index.php?topic=4114.msg20026#msg20026

[참조] http://www.devkorea.co.kr/bbs/board.php?bo_table=m03_qna&wr_id=31752

반응형
Posted by blueasa
, |

NGUI 를 사용하면서 일반 오브젝트와 UI 오브젝트의 입력(터치)을 어떻게 처리해야 할지 알아본다.



일단, 보통은 게임에서 사용하는 Main Camera와 NGUI > Create UI 를 통해 생성되는 2D Camera(UI Camera) 두개(혹은 그 이상)를 사용할 것이다.


당연히 UICamera에 추가되는 Widget들은 UICamera 의 통제에 의해 OnHover, OnClick 등의 이벤트를 받는다.


하지만 게임오브젝트를 선택하려면? 당신은 여러가지의 고민을 하게된다.

'UI의 이벤트를 받지 않으려면?', '혹은 UI를 클릭했을때 게임오브젝트의 클릭을 무시하려면?' 등등...

하여, 이를 해결하기 위해 Picking Manager 라던지 NGUI의 메시지를 무시하는 플래그를 작성하던지의 시도를 해볼것이다.


NGUI는 이 상황에 대해 다음을 권고한다.


'모든 카메라에 UICamera 컴포넌트를 추가하세요!' 


일단 NGUI:UICamera 의 내용을 보면, UI카메라에 추가되었을경우엔 UI 들에게, Main Camera에 추가하면 인게임 오브젝트들에게 특정 이벤트 메시지를 보낸다고 써져있다. 본문


이벤트는 다음 링크를 참고한다. 이벤트



실제로 테스트 해본 결과,


1. 같은 레이어상의 UI와 non-UI 오브젝트(in-game object)로 테스트 시.

2개의 카메라(Main-Camera, UI-Camera)에 각각 UICamera 컴포넌트를 포함시킨후 실험.

NGUI Widget 툴을 통해 UI-Camera에 바탕 윈도우와 버튼을 하나 추가했다.

테스트를 위해 2개의 큐브를 씬에 추가. 스크립트를 작성하되, void OnClick() 함수를 추가했다.



테스트 결과, 버튼 영역을 클릭했을때, UIButton만 동작되었다.

게임 오브젝트 클릭시 OnClick이벤트가 정상 동작되었으며, 깊이에 따라 먼저 클릭된 게임오브젝트만 동작되었다.

버튼 영역을 제외한 UI윈도우 영역은 클릭테스트에 제외되며, 게임 오브젝트가 하단에 존재하면 게임오브젝트 이벤트가 호출된다.


- UI윈도우도 클릭테스트에 포함시키기 위해서는 Add Component > Physics > Box Collider 를 추가해준다. 추가후에는 윈도우에서 이벤트를 처리하기 때문에 윈도우 영역 클릭시 게임 오브젝트는 이벤트를 받지 않는다.


- 버튼이 isEnable=false; 되어있다면, 이벤트를 받지 않는다.


2. UI 부분을 다른 레이어로 세팅.

- 동일한 레이어일때와 결과가 같다.



즉, 이왕 NGUI를 사용한다면, 모든 카메라에 UICamera 컴포넌트를 추가하고, 입력이 필요한 오브젝트 마다 이벤트 함수를 추가해주자.



출처: http://toymaker.tistory.com/entry/NGUI-UI와-일반-오브젝트의-터치-이벤트-처리 [ToyMaker]

반응형
Posted by blueasa
, |

SHADDERRRRS! Well that is it, I’m caught in shader land. The thing is, I don’t know jack **** about them. What I am missing mostly from Flash in Unity are filters like blur, drop shadow and glow. How you would go about doing that in Unity would be with shaders (I guess), so I stuck my nose in them. Here is my first version of a Blur filter/shader.

 

Shader "Unlit/Transparent Colored Blurred"
{
  Properties
  {
    _MainTex ("Base (RGB), Alpha (A)", 2D) = "white" {}
    _Distance ("Distance", Float) = 0.015
  }
 
  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 vertexProgram
      #pragma fragment fragmentProgram
 
      #include "UnityCG.cginc"
 
      struct appdata_t
      {
        float4 vertex : POSITION;
        float2 textureCoordinate : TEXCOORD0;
        fixed4 color : COLOR;
      };
 
      struct vertexToFragment
      {
        float4 vertex : SV_POSITION;
        half2 textureCoordinate : TEXCOORD0;
        fixed4 color : COLOR;
      };
 
      sampler2D _MainTex;
      float4 _MainTex_ST;
      float _Distance;
 
      vertexToFragment vertexProgram (appdata_t vertexData)
      {
        vertexToFragment output;
        output.vertex = mul(UNITY_MATRIX_MVP, vertexData.vertex);
        output.textureCoordinate = TRANSFORM_TEX(vertexData.textureCoordinate, _MainTex);
        output.color = vertexData.color;
        return output;
      }
 
      fixed4 fragmentProgram (vertexToFragment input) : COLOR
      {
        float distance = _Distance;
        fixed4 computedColor = tex2D(_MainTex, input.textureCoordinate) * input.color;
        computedColor += tex2D(_MainTex, half2(input.textureCoordinate.x + distance , input.textureCoordinate.y + distance )) * input.color;
        computedColor += tex2D(_MainTex, half2(input.textureCoordinate.x + distance , input.textureCoordinate.y)) * input.color;
        computedColor += tex2D(_MainTex, half2(input.textureCoordinate.x , input.textureCoordinate.y + distance )) * input.color;
        computedColor += tex2D(_MainTex, half2(input.textureCoordinate.x - distance , input.textureCoordinate.y - distance )) * input.color;
        computedColor += tex2D(_MainTex, half2(input.textureCoordinate.x + distance , input.textureCoordinate.y - distance )) * input.color;
        computedColor += tex2D(_MainTex, half2(input.textureCoordinate.x - distance , input.textureCoordinate.y + distance )) * input.color;
        computedColor += tex2D(_MainTex, half2(input.textureCoordinate.x - distance , input.textureCoordinate.y)) * input.color;
        computedColor += tex2D(_MainTex, half2(input.textureCoordinate.x , input.textureCoordinate.y - distance )) * input.color;
        computedColor = computedColor / 9;
 
        return computedColor;
      }
      ENDCG
    }
  }
}

It works ok, with a lot of restrictions. First, you can only use it for NGUI UITextures. I would love it to work with UISPrites, but they all share the same atlas, so if you blur one sprite you blur them all! Also, for now, you should leave a padding of 10 transparent pixels around your texture for a better effect.
 

ShaderBlurred

The Distance parameter is relative to the size of your texture so correct values will change from one texture to the other. Anyway you have it, I will keep working on it, but if you see anything that can be improved, don’t be afraid to tell me, I would really like to make it better.



[출처] http://www.zedia.net/2013/blur-filter-for-uitexture-in-ngui/

반응형
Posted by blueasa
, |

다루는 내용

- Sprite Slice

- Anchor

- UI Tweener

- TypeWriter Effect


말풍선은 게임의 많은 곳에서 사용된다. 튜토리얼을 진해할 때, NPC와 대화 할 때 등.. 이러한 말 풍선을 NGUI를 사용하면 쉽게 만들 수 있다. 아래와 같이 말풍선이 커지는 트위닝과 글씨가 자동으로 써지는 타이핑 효과 그리고 말풍선 배경이 문구의 크기와 위치에 맞게 변하도록 하는 앵커의 개념을 이해한다.

준비물

NGUI, 캐릭터 이미지, 말풍선 이미지, 폰트 (NGUI는 상용 플러그인이므로 예제를 첨부할 수 없음.) 















NGUI 아틀라스 만들기

먼저 위의 그림들을 NGUI를 활용하여 아틀라스를 만든다. 메뉴의 NGUI - Open - Atlas Manker 를 차례로 클릭하여 아틀라스 메이커를 실행한다. 그리고 사용할 이미지들을 선택 하면 아래 그림처럼 Add가되고 선택 완료 후 끝으로 Create 버튼을 클릭하면 아틀라스를 저장할 곳을 묻는다. 적당한 곳에 저장하면 끝난다.


나인패치(9Patch)

추가한 말풍선 스프라이트는 작은 크기인데 어떻게 글자 수에 맞워서 늘어날 수 있을까? 그리고 늘어난 이미지는 왜 꺠져보이지 않을까? 말풍선을 9개 조각으로 나누어 활용하였기 때문이다. 나인패치 개념은 스프라이트 하나를 9족가으로 나무어 각 모서리 4부분은 고정으로 사용하고 나머지 5부분은 늘어나는 데 사용된다. 말풍선 뿐아니라 게임에서 사용하는 버튼도 9패치를 사용할 수있다. 여러 상황마다 버튼의 크기가 달라질 수 있는데 그때마다 새로운 버튼을 만들어 추가하는 것은 비효율적이다. 나인 패치를 이용하면 하나의 버튼 스프라이트로 다양한 크기의 버튼을 만들어낼 수있다. 

스프라이트를 9조각으로 나누는 방법은 간단하다. 생성한 스프라이트를 선택하고 Edit 버튼을 누른다. 그럼 UI Atlas 인스펙터가 보인다. 중간에 Border 값 들을 조절하면 점선으로 나눌 부분을 지정할 수 있게된다. 9개로 나눌 부분을 지정이 끝났다면 다시 스프라이트로 돌아와 스프라이트의 Type를 Sliced로 변경한다. 그리고 아래의 Size 에서 크기를 조절하면 9개의 영역을 나눈데로 크기가 변하는 것을 확인할 수 있다.


앵커(Anchor)

텍스트가 말풍선 스프라이트 밖으로 삐져나가면 안된다. 말풍선은 말풍선안의 텍스트 포함해야한다. 이것을 해결하기 위해 2가지 방법이 있다. 먼저 말풍선의 크기를 고정하고 메세지 라벨의 크기도 그 안에서만 보이도록 하는 것이다. 하지만 고정된 말풍선 영역 안에서 텍스트의 양이 많다면 자연적으로 텍스트가 작아지는 단점이있다. 이 방법을 사용하려면 라벨의 Overflow를 shrink로 설정하고 Size를 말풍선에 맞게 수정해야 한다. shrink로 설정하였기 때문에 텍스트는 설정 영역 밖으로 나가지 않는다. 또 한가지 방법은 텍스트는 글자 수에 따라 자유롭게 늘어날 수있고 이것에 대응하여 말풍선 배경의 사이즈가 조절되는 방식이다. 첫 번째 방법은 텍스트가 많을 경우 글씨 크기가 작아지는 단점이있다. 그래서 보통 두 번째 방법을 사용한다. 크기가 자유로은 텍스트의 크기를 말풍선이 따라가기 위해서 필요한 것이 앵커이다. 말풍선은 이미 9패치로 자유롭게 크기 조절이 가능한 상태이다. 그러므로 말풍선 스프라이터의 앵커를 텍스트에 맞추면 된다. 라벨의 Overflow는 Resize freely로 설정한다. 

앵커를 설정하는 것은 어렵지 않다. 위 그림처럼 말풍선 스프라이트의 인스펙터에서 간단히 설정한다. 타입은 None, Unified, Advenced 가 있다. None는 앵커를 사용하지 않는 것이다. Unfied는 단일 타겟을 4방향에서 지정한 수치만큼 앵커를 잡는 것이다. 마지막으로 Advenced는 4방향을 각각 원하는 타겟을 잡고 수치를 지정하는 방식이다. 타겟을 서로 다르게 지정할 수도있고 지정하지 않을 수도있다. Excute 는 앵커가 동작하는 시점을 말한다. OnEnable 은 해당 오브젝트가 꺼진상태에서 활성화 될 때 호출, OnUpdate는 매 프래임마다, OnStart는 씬이 시작할 때 한 번 호출된다. 이번 예제에서는 텍스트의 크기가 시간이 따라 변화하면서 그에 맞추어 말 풍선 스프라이트의 앵커도 따라가야하기 때문에 OnUpdate로 설정하였다.


Tween Scale

NGUI의 라벨이나 스프라이트를 애니메이션할 수있게 돕는 컴포넌트이다. 크기에대한 애니메이션을 Tween Scale로 처리하고 그 밖에 Tween Position으로 위치 애니메이션, Tween Alpha로 투명도 애니메이션을 할 수 있다. 이번 예제에서 사용하는 Tween Scale은 말풍선이 캐릭터 위에서 커지는 애니메이션을 한다.

스케일 애니메이션을 할 말풍선 스프라이트에 Tween Sacle 컴포넌트를 추가한다. From 에서 시작할 크기를 지정하고 To에 끝나는 크기를 지정한다. 시작 크기를 0.5 끝 크기를 1로 설정하였다. 이렇게히면 0.5에서 1까지 말풍선의 크기가 변하게 된다. Plya Style 은 애니메이션을 반복할지 여부를 설정하는 옵션이다. 기본적으로 Once로 설정이 되어있어서 애니메이션은 한 번만 실행된다. Loop는 애니메이션을 계속 반복하는 것이고 PingPong은 From -> To ->From ->To 반복적으로 From 에서 To 그리고 To 에서 From 으로 왕복한다. Animation Curve에서는 애니메이션 이징 그래프가 등장한다. 시간에 따른 변화량을 그래프로 표현한 것이다. 클릭해면 편집창이 뜨고 초록색 선위에 오른쪽버튼을 클릭하여 Add key를 선택한다. 그리고 선을 자유자제로 조절할 수있다. Duration은 실행 시간이다. 기본적으로 1초가 세팅되어있다. Start delay는 지연시간을 의미한다. Start delay 시간 만큼 지난 후 애니메이션을 실행 시킬 수 있다. Ignore TimeScale 옵션을 체크하면 타임스케일의 영향을 받지 않고 애니메이션을 한다. 예를 들어, 게임 중 볼륨이나 진동 옵션을 변경하기 위해 설정 대화상자를 띄었을 때 게임은 일시 정지되고 설정 대화상자 안의 스프라이트나 라벨들은 시간에 따른 스케일이나 위치등의 애니메이션을 하기위해서는 해당 옵션이 체크되어있어야 한다. 마지막으로 On Finished 는 애니메이션이 종료된 후 호출할 메서드를 선택할 수 있다. 매서드가 포함된 스크립트가 붙은 오브젝트를 드래그하여 넣고 매서드를 선택하면 된다.


원하는 상황에서 Tween 실행

위 그림에서 컴포넌트의 체크가 꺼져있다. 그러므로 실행되지 않는다. 게임중에 켜는 시점을 코드로 제어하여 컴포넌트를 켤 수 있다. 그러면 원하는 상황에 애니메이션이 가능하다. 그런데 애니메이션이 끝나고 다시 켠다고해서 애니메이션이 동작하지는 않는다. 이유는 컴포넌트가 켜지는 순간 인스펙터의 옵션들의 정보를 바탕으로 애니메이션이 시작되는데 애니메이션이 끝나고 나중에 다시 켜더라도 옵션들은 이전의 정보이기 때문이다.


해결책

컴포넌트를 켜고 끄는 방식으로 애니메이션을 제어하지 말고 ResetToBeginning 과 PlayForward를 사용하여 제어한다. 위처럼 인스펙터에서 옵션들을 설정한 뒤 컴포넌트를 끈 상태로 놔두고 게임을 실행한다. 코드에서는 해당 애니메이션을 할 상황이 됐을 때, PlayForward 를 호출 해 애니메이션을 실행한다.

1
2
tweenScale.ResetToBeginning();
tweenScale.PlayForward();

다시 사작하고 싶다면 ResetToBeginning 으로 초기화 후 PlayForward로 실행할 수 있다. 오래된 NGUI 버전에서는 Play로 실행했지만 현재는 PlayForward 와 PlayReverse 로 분리되었다. 반대로도 애니메이션을 실행할 수 있는 것이다. PlayReverse 를 사용해 애니메이션을 반대로 실행했다면 이 상황에서 PlayForward를 하고싶을 떄에는 굳이 ResetToBeginning 를 할 필요 없이 바로 PlayForward해도 동작한다.


타이핑 효과

Typewriter Effect 컴포넌트를 추가하여 텍스트에 타이핑 효과를 적용할 수 있다. charsPerSecond 옵션은 초당 표시할 글자 수이다. 수치가 높을 수록 빠른 타이핑 효과가 나타난다. fadeInTime 옵션은 글자가 알파가 적용되어 나타나는 시간이다. 딱딱한 타이핑효과가 아니라 부르럽게 텍스트가 나타난다. delayOnPeriod 옵션은 . ! ? 로 문장이 끝났을 때 지연되는 시간이다. 설정된 시간이 지난 후 다은 타이핑 효과가 계속 된다. delayOnNewLine 옵션은 텍스트가 다음 행으로 넘어갈 때 지연되는 시간이다. 그리고 타이핑 효과에도 scrollView 옵셥으로 NGUI 스크롤을 적용할 수 있다. 


타이핑 효과의 역설

텍스트에 타이핑 효과를 적용하는 이유는 한 글자씩 보이게 하기 위해서인데, 그러기 위해선 텍스트를 할당해야 한다. 하지만 할당하는 순간 UI에 텍스트는 이미 모두 보여지는 상태이다. 잠깐이지만 텍스트들이 모두 보이고 없어진다 그리고 타이핑 효과가 진행된다. 이것 때문에 말풍선 전체가 잠깐 깜빡이는 것처럼 보인다. 이것을 해결하기 위해 순서를 바꿔서 실행한다. 기존에는 스케일 커지기 -> 텍스트 할당 -> 타이핑 효과의 순서로 진행 했다. 이것을 텍스트 할당 -> 타이핑 효과 -> 스케일 애니메이션의 순서로 변경하였다. 물론 이것은 편법이다. 



출처: http://teddy.tistory.com/entry/NGUI-쉽게-말풍선-만들기 [Teddy Games]

반응형
Posted by blueasa
, |

[링크] https://github.com/pumperer/InfiniteList_NGUI



Description

A component that runs on top of NGUI's UIScrollView & UITable classes for Unity3D (i.e. It requires NGUI & Unity3D) can be used with dynamic data.

Instead of instantiating a Prefab for each row in the list we are instantiating a fixed pool of objects that will be reused according to the scroll direction.

Best suited for Mobile (tested on both iOS & Android).

Features

  • Infinite scrolling with clipping panel
  • Only fixed height cells are supported for now
  • Basic Scroll indicator
  • Quick jump (selecting a start point)
  • Simple sections implementation (section height need to be equal to the item height)
  • Click item callbacks
  • Tested on Unity v4.2.2 & Unity v4.3 and NGUI v3.0.9f7

The Demo

This demo package requires both Unity3D http://unity3d.com and NGUI http://www.tasharen.com/?page_id=140 to be installed. video: https://www.youtube.com/watch?v=5xFVJqzp0kY

To run the demo:

  1. Create a new Unity Project (preferably mobile i.e. iOS or Android)
  2. Import NGUI including its examples as the demo uses the atlas's from the examples
  3. Import InfiniteListDemo folder or simply double click on InfiniteListDemoPackage
  4. Run the scene (InfiniteListDemo)

The demo package is released under the MIT License: http://opensource.org/licenses/MIT

Example of app using this component is Avatar Messenger for Android (Contacts list view) which is a free app on Google Play: https://play.google.com/store/apps/details?id=com.orange.labs.avachat

Main Classes & Methods in the Demo

InfiniteListPopulator

The main controller script that can be attached to a gameobject (e.g. the panel)

Some of the main methods included:

Initializes the list (also can be called to refresh the list with new data)

public void InitTableView(ArrayList inDataList, List<int> inSectionsIndices, int inStartIndex)

Parameters:

  • inDataList: the generic list of our data (you can change it to any type you want… just make sure to change the member variables types for dataList & OriginalData)* inNumberOfSections: number of sections (int)
  • inSectionIndices: List of integers. The start index of each section (not as fancy as indexpath in iOS but did the job for me)
  • inStartIndex: where to start

Refresh the list without changing the data (list start at startIndex value)

public void RefreshTableView()

Individual methods for changing the parameters if needed

public void SetStartIndex(int inStartIndex)
public void SetOriginalData(ArrayList inDataList)
public void SetSectionIndices(List<int> inSectionsIndices)

You can include section titles values.. or if you have more detailed sections seperators you can change the implementation of PopulateListSectionWithIndex

string GetTitleForSection(int i)
void PopulateListSectionWithIndex(Transform item, int index)

You can do your implementation of what to populate your row item with (in the demo we simply set a label to string value from our datalist array). Simply change InfiniteItemBehaviour (mentioned later below) to include more items as you want.

void PopulateListItemWithIndex(Transform item, int dataIndex)

Events that can be listened to.

public event InfiniteItemIsPressed InfiniteItemIsPressedEvent;
public event InfiniteItemIsClicked InfiniteItemIsClickedEvent;

InfiniteItemBehaviour and InfiniteSectionBehaviour

Scripts attached to the row item prefab & section prefab (Note: the item prefab need to be tagged as "listItem" and the section prefab as "listSection")

Both checks for the visiblity of the item when the list start scrolling and notifiy the InfiniteListPopulator when the items becomes invisible. you can change use them as a template and include more labels, sprites or textures.

반응형

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

[펌] Blur filter for UITexture in NGUI  (0) 2017.02.09
[펌] NGUI 쉽게 말풍선 만들기  (0) 2017.02.03
NGUI CoverFlow(with Reflection Shader)  (0) 2016.10.11
[Link] Unity-NGUIExtension  (0) 2016.10.10
[펌] Smart Localization with NGUI  (0) 2016.09.26
Posted by blueasa
, |

首先原帖子在这里:
http://game.ceeger.com/forum/read.php?tid=1383
 
这楼主做得非常好了,我都不知道怎么优化才好,但是本人是厌恶OnGUI主义者,所以决定要把一切OnGUI的东西根除...
 
然后附加了镜面效果,看着还行,不说那么多先来个图:
1
 
2
 
3
 
下面是NGUI的排布
5
 
4
 
主要代码,红色为修改的部分
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
public class NGUICoverFlow : MonoBehaviour {
    private List<GameObject> photos = new List<GameObject>();
    private int photosCount = 5;
 
    private int currentIndex = 0;
    private float MARGIN_X = 3f;  //plane 之间的间隔
    private float ITEM_W = 10f;   //plane长宽为10M(10个单位长度)
 
    private float sliderValue = 4f;
    public UISlider uiSlider;
    void Start()
    {
        loadImages();
       //uiSlider.numberOfSteps = photosCount; //这里可设成Steps模式  随个人喜好
    }
 
    void loadImages()
    {
        for (int i = 0; i < photosCount; i++)
        {
            GameObject photo = GameObject.CreatePrimitive(PrimitiveType.Plane);
            photos.Add(photo);
            photo.layer = 14; //我的相片全部作为一个单独的层  这样镜面渲染就好办了
            photo.transform.eulerAngles = new Vector3(-90f, 0f, 0f);
            photo.transform.localScale = new Vector3(1.5f, 1f, -1f);   //根据图片设定长宽比,z:-1,使图正向
            photo.renderer.material.mainTexture = Resources.Load("photo" + i.ToString(), typeof(Texture2D)) as Texture2D;
            photo.transform.parent = gameObject.transform;
        }
        moveSlider(photos.Count / 2);
    }
 
    void moveSlider(int id)
    {
        if (currentIndex == id)
            return;
        currentIndex = id;
 
        for (int i = 0; i < photosCount; i++)
        {
            float targetX = 0f;
            float targetZ = 0f;
            float targetRot = 0f;
 
            targetX = MARGIN_X * (i - id);
            //left slides
            if (i < id)
            {
                targetX -= ITEM_W * 0.6f;
                targetZ = ITEM_W * 3f / 4;
                targetRot = -60f;
 
            }
            //right slides
            else if (i > id)
            {
                targetX += ITEM_W * 0.6f;
                targetZ = ITEM_W * 3f / 4;
                targetRot = 60f;
            }
            else
            {
                targetX += 0f;
                targetZ = 0f;
                targetRot = 0f;
            }
 
            GameObject photo = photos;
            float ys = photo.transform.position.y;
            Vector3 ea = photo.transform.eulerAngles;

            iTween.MoveTo(photo, new Vector3(targetX, ys, targetZ), 1f);
            iTween.RotateTo(photo, new Vector3(ea.x, targetRot, targetZ), 1f);
        }
    }
   public void OnSliderChange(float value)

   {
       Debug.Log(value);
       moveSlider((int)(value * photosCount));
   }
}
下面是uiSlider的设置

 
镜面效果是我从某个网页找到的,请点击看:
http://blog.163.com/lnwanggang@yeah/blog/static/165332162201010611107883/
这个效果写得很好,我就不复制黏贴了,
主要是搞一个shader和一个调用的文件MirrorReflection.cs:
其实这两个东西到底什么意思我也没看懂,我会吐槽么

反正我是拿来用了
其实感觉不写shader也可以  直接拿FX/Mirror Reflection那个来用 
但是那个MirrorReflection.cs是一定要写的
几个参数默认就好了,只有m_ReflectLayers这个设置为picture的层就行了 


不过我对比过好像这个多了一句shader语句好像是image效果的意义不明
 
再自己用ps新建一个64*64的图片
rgb为106,107,106, 整个图片的透明度为40%,然后保存成png放入场景中,作为镜面的材质色

一定要
最后调整一下各个方向的位置和角度,
搞定!~ 自己动手丰衣足食   项目我就不放出来了



[출처] http://www.ceeger.com/forum/read.php?tid=1411

반응형
Posted by blueasa
, |



[Link] https://github.com/kimsama/Unity-NGUIExtension

반응형
Posted by blueasa
, |