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

카테고리

분류 전체보기 (2831)
Unity3D (880)
Programming (479)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (187)
협업 (64)
3DS Max (3)
Game (12)
Utility (140)
Etc (98)
Link (32)
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

Android Manifest File

Unity3D/Tips / 2015. 8. 25. 15:37


링크1 : http://android007.tistory.com/8

링크2 : http://hyeonstorage.tistory.com/151

반응형
Posted by blueasa
, |


Error building Player:NullReferenceException : object reference not set to an instance of an object


위와 같은 에러가 나서 찾아보니 AndroidManifest.xml 파일안에 <application> </application> 태그가 없기 때문이라고 한다.



참조 : http://devmae.tistory.com/376

반응형
Posted by blueasa
, |

Command line arguments

Unity 편집기를 그것이 연 상태로 특정 태스크를 실행하도록 만들기 위해서 커맨드 라인 아규먼트와 함께 시작하는 것이 가능합니다. 이것은 자동적인 게임 빌드, 테스트 스윗 등등을 허용합니다. below를 살펴보시기 바랍니다.

게다가 Unity와 함께 구축되어 있는 혼자하는 게임은 어떤 커맨드 라인 파라미터를 허용합니다. below를 살펴보시기 바랍니다.

editor

Unity Editor command line arguments

-batchmode

Unity를 batch 모드에서 실행합니다. 이것은 항상 그것이 어떠한 팝업 윈도우도 나타나지 않도록 함에 따라 그리고 어떠한 사람의 개입의 필요를 제거함에 따라 다른 커맨드 라인 아규먼트와 함께 결합되어 사용되야 합니다. 스크립트 코드의 실행 동안에 하나의 예외가 발생할 때 에셋 서버 업데이트는 실패하거나 또는 다른 오퍼레이션 들도 실패하고 Unity는 즉시 1을 리턴 코드로 하고 종료합니다.

Batch 모드에서 Unity는 그것의 로그가 콘솔로 나가는 버전을 쓸 것입니다. 완전한 디버그 정보를 위해서 Unity의 Log Files를 보시기 바랍니다.

-quit

다른 커맨드 라인 아규먼트의 실행을 끝내면서 Unity를 깨끗하게 멈춥니다.

-buildWindowsPlayer

혼자서하는 윈도우즈 플레이어를 구축합니다 (예 -buildWindowsPlayer path/to/your/build.exe).

-buildOSXPlayer

혼자서하는 윈도우즈 플레이어를 구축합니다 (eg, -buildOSXPlayer path/to/your/build.app).

-importPackage //packagepath//

주어진 package를 불러옵니다. 어떠한import 다이아로그도 보여지지 않습니다.

-createProject //pathname//

주어진 경로에 빈 프로젝트를 생성합니다.

-projectPath //pathname//

주어진 경로에 프로젝트를 오픈 합니다.

-assetServerUpdate //IP[:port] projectName username password [r <revision>]//

IP:port에 의해 주어진 Asset Server 에서 프로젝트의 업데이트를 강요합니다. 포트는 선택적이로 주어지지 않았다면 그것은 스탠다드 원(10733)이 되도록 가저됩니다. 사용자가 옳은 프로젝트와 작업하고 있다는 것을 확신시키기 위해서 -projectPath 아규먼트와 함께 결합된 이 명령을 사용하는 것은 충고될 수 있습니다. 프로젝트 이름이 주어지지 않으면 Unity에서 열어진 마지막 프로젝트가 사용됩니다. -projectPath에 의해 주어진 경로에서 프로젝트가 존재하지 않으면 하나가 자동적으로 생성됩니다.

-executeMethod //ClassName.MethodName//

Unity가 시작되자마자static method를 실행하고 선택적인 에셋 서버 업데이트가 실행된 후에 프로젝트 폴더는 열려집니다. 이것은 계속적인 통합을 하기 위해 사용될 수 있습니다 : Unit 테스트, 빌드 만들기, 데이터 준비하기. 사용자가 커맨드 라인 프로세스로부터 에러를 리턴하고 싶다면 사용자는 Unity가 1과 함께 종료하도록 하는 예외를 던지거나 또는 0이 아닌 코드와 함께EditorApplication.Exit를 콜합니다.

-executeMethod를 사용하기 위해서 _사용자는 편집기 폴더의 스크립트와 클래스의 static 함수를 가질 필요가 있습니다_.

// C# example
using UnityEditor;
class MyEditorScript
{
     static void PerformBuild ()
     {
         string[] scenes = { "Assets/MyScene.unity" };
         BuildPipeline.BuildPlayer(scenes, ...);
     }
}
// JavaScript example
static void PerformBuild ()
{
    string[] scenes = { "Assets/MyScene.unity" };
    BuildPipeline.BuildPlayer(scenes, ...);
}

-exportPackage

주어진 경로에서 하나의 패키지를 export 합니다. _ 사용법:_ -exportPackage exportAssetPath exportFileName
_Where:_ _exportAssetPath:_ unity 프로젝트에서 export하는 폴더입니다 
_exportFileName:_ 패키지 이름입니다 

현재 그것은 전체 폴더만을 export하는 것을 지원합니다.

-nographics //(Windows only)//

Batch 모드에서 실행할 때 그래픽 디바이스를 초기화하지 않아야 합니다. 이것은 GPU를 가지지 않는 기계 위에서 사용자의 자동 워크플로우를 실행하도록 하는 것을 가능하게 합니다.

Example usage

Back 모드에서 Unity를 실행합니다. MyEditorScript.MyMethod 메서드를 실행하고 완료시 종료합니다.

_Windows:_
C:\program files\Unity\Editor>Unity.exe -quit -batchmode -executeMethod MyEditorScript.MyMethod

_Mac OS:_
/Applications/Unity/Unity.app/Contents/MacOS/Unity -quit -batchmode -executeMethod MyEditorScript.MyMethod

Batch 모드에서 Unity를 실행합니다. 주어진 프로젝트 경로를 사용하고 에셋 서버로부터 업데이트 합니다. 모든 에셋이 다운로드 되어지고 에셋 서버로부터 불려진 후에 주어진 메서드를 실행합니다. 메서드가 실행을 마치면 자동적으로 Unity를 종료합니다.

/Applications/Unity/Unity.app/Contents/MacOS/Unity -batchmode -projectPath ~/UnityProjects/AutobuildProject -assetServerUpdate 192.168.1.1 MyGame AutobuildUser l33tpa33 -executeMethod MyEditorScript.PerformBuild -quit

player

Unity Standalone Player command line arguments

Unity와 함께 구축된 혼자서하는 플레이어는 커맨드 라인 아규먼트를 이해합니다:

-batchmode

게임을 "headless" 모드로 실행합니다. 게임은 어떤 것도 보여주지 않을 것이면 사용자 입력을 허용하지 않을 것입니다. 이것은networked games의 실행하는 서버를 위해서 대부분 유용합니다.

-force-opengl //(Windows only)//

심지어Direct3D가 가능할 때도 게임이 렌더링을 위해서OpenGL을 사용하도록 만듭니다. 보통Direct3D이 사용됩니다; 그리고Direct3D 9.0c이 가능하지 않는 경우에만OpenGL이 사용됩니다.

-single-instance //(Windows only)//

게임의 한 인스턴스가 한 번에 실행되도록 합니다. 또다른 게임이 벌써 실행되고 있다면 그것을 -single-instance와 함께 다시 시작하는 것은 기존에 존재하고 있는 것에 포커스를 둘 것입니다.

-nolog //(Windows only)//

Output 로그를 생성하지 않습니다. 주로 output_log.txt는 실행될 수 있는 게임 옆에 *_Data 폴더에 씌여집니다. 거기서Debug.Log 결과는 프린트 됩니다.

-force-d3d9-ref //(Windows only)//

Direct3D의 "Reference" 소프트웨어 렌더러를 사용해서 게임을 실행하도록 만듭니다. DirectX SDK는 이것이 작동하도록 하기 위해서 설치될 필요가 있습니다. 이것은 자동 테스트 스윗을 만들기 위해 매우 유용합니다. 거기서 사용자는 렌더링이 무슨 그래픽 카드이냐에 상관없이 정확하게 같은 것을 하는 것을 확실시하고 싶어합니다.

-adapterN //(Windows only)//

게임이 또다른 디스플레이에서 전체 스크린으로 실행되도록 허용합니다. 거기서 N은 디스플레이 숫자를 의미합니다.

-popupwindow //(Windows only)//

윈도우는 팝업 윈도우로서 생성될 것입니다 (프레임 없이).



출처 : http://openwiki.kr/unity/commandlinearguments

반응형
Posted by blueasa
, |

유니티에서 쓸 WebView를 찾아보다가 유료지만 괜찮아 보이길래 남겨 놓음.


수익이 $100k(대략 1억원) 이하면 Free 버전 써도 된다고 하니 나중에 한 번 건드려 봐야지..


[링크] http://www.awesomium.com/


[참조]

http://www.devkorea.co.kr/bbs/board.php?bo_table=m03_qna&wr_id=29578

http://labs.awesomium.com/unity3d-integration-tutorial-part-1/


반응형
Posted by blueasa
, |

Why doesn’t my particle system show in front of my sprites??

Particle System Sort LayerThis one had me befuddled for a little while. I could not figure out why my particle system was not showing up in front of my sprites for the life of me. I had the “Layer” set properly but I couldnot find a place to set the “Sorting Layer”. I came across some other folks who were saying you had to set the sorting layer manually in code so theparticle system would show up where it needed to (sorry, I can’t remember the references!). Okay, that seems easy enough, let’s see if we can figure that out. It looks like we can do that via the following code. The “sortingLayerName” is just a string of a sorting layer you have defined in Unity and the “sortingOrder” is an integer that specifies the z-order in that sorting layer. The higher the number, the closer the object “looks” to you.


1
2
particleSystem.renderer.sortingLayerName = sortingLayerName;
particleSystem.renderer.sortingOrder = sortingOrder;

So now let’s just make this into a script so we can easily apply it to all particle systems we create.

I put the following code into a file named “ParticleSystemFix.cs” and attached it to any particle systems I create.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using UnityEngine;
using System.Collections;
 
public class ParticleSystemFix : MonoBehaviour {
 
public string sortingLayerName;
public int sortingOrder;
 
/**
 */
void Start() {
    particleSystem.renderer.sortingLayerName = sortingLayerName;
    particleSystem.renderer.sortingOrder = sortingOrder;
    enabled = false;
  }
}

I’ll usually tell a script to disable itself once it is done initializing or if the code in the Update() function starts to be skipped because of a certain condition. I’m sure there has to be a slight performance advantage to doing this…every little bit helps.  Plus it lets me know if something is executing properly when I expect the script to become disabled.

Particle System Sort LayerNow, just attach this script to any particle system; there in the inspector, you can define a “sortingLayerName” and “sortingOrder” on the “ParticleSystemFix”.  I used a large number like 999 as my “sortingOrder” since I want my particle systems to appear on top of all my sprites.

 

 

Particle System Sort LayerMake sure that what you pass into the “sortingLayerName” is defined in Unity!

That is about it, as long as the “sortingLayerName” for your particle system is where it needs to be hierarchically, your particle system should appear on top of the sprites.

 

 

 

 


출처 : 

반응형
Posted by blueasa
, |

UnityToolbag

Unity3D/Plugins / 2015. 7. 20. 19:58


Link : https://github.com/nickgravelyn/UnityToolbag



UnityToolbag

This repo is a host for any little Unity scripts I write that are simple and easy for others to leverage. Each folder has its own README to explain the usage in more depth than here. All scripts are being written with Unity 5.0 and may or may not work in earlier versions.

Features

  • CacheBehaviour - A drop-in replacement for MonoBehaviour as a script base class that provides caching of all standard properties.
  • Dispatcher - Provides a mechanism for invoking code on the main thread from background threads.
  • DrawTitleSafeArea - Simple component you add to a camera to render the title safe area.
  • EditorTools - Misc tools for making it easier to build editor UI.
  • ExclusiveChildren - Helper script for managing objects in a hierarchy that represent mutually exclusive options (like a set of menu screens)
  • Future - Simple implementation of the future concept.
  • GameSaveSystem - A helper system for game saves to provide automatic backups and background thread processing along with better game save file paths.
  • ImmediateWindow - An editor window that allows executing manual C# snippets.
  • ScriptableObjectUtility - An editor class to help with creating ScriptableObject subclasses.
  • SimpleSpriteAnimation - A very basic system for a simpler frame based animation for Unity's 2D system.
  • SnapToSurface - Editor tools to assist in positioning objects.
  • SortingLayer - Tools for working with Unity's new sorting layers.
  • TimeScaleIndependentUpdate - Components to make it easier to continue animations whenTime.timeScale is set to 0 (i.e. paused).
  • UnityConstants - Tool for generating a C# script containing the names and values for tags, layers, sorting layers, and scenes.
  • UnityLock - Basic tool for locking objects in the scene to minimize accidental edits while working.

Usage

Simply clone the repository into the 'Assets' folder of a Unity project and you're good to go. If you're already using Git, you can use a submodule to check out into Assets without the Toolbag getting added to your repository.

Alternatively you can just cherry pick the features you want and copy only those folders into your project. Be careful, though, as some of the features may depend on others. See the individual feature README files to find out.

Any component types are exposed through the component menu under UnityToolbag:

ComponentMenu.png

Contributing

Feel free to contribute fixes, updates, or enhancements to the code via pull request. New tools or utilities are welcome provided they are useful to a variety of people. Please read the contribution guide for further details.

Shameless Plug

If you find any code in here to be useful and feel so inclined, you can help me out by picking up a copy of my company's first game Shipwreck. Absolutely not required (this code is free) but definitely appreciated. :)

반응형
Posted by blueasa
, |

Sorting Layer 사용하기

Unity3D / 2015. 7. 20. 19:55

링크 : http://dellwon.tistory.com/entry/Unity3D-Sorting-Layer-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0


링크 : https://unity3d.com/kr/learn/tutorials/modules/beginner/2d/sorting-layers

반응형

'Unity3D' 카테고리의 다른 글

Player Settings  (0) 2013.01.15
Layer  (0) 2013.01.15
간단한 Nav Mesh 예제  (0) 2012.11.21
런타임 중 텍스쳐 교체  (0) 2012.11.20
상체 애니메이션 덧붙이기(AddMixingTransform)  (2) 2012.11.16
Posted by blueasa
, |

유니티로 개발을 하다보면 스크립트에서 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
, |