블로그 이미지
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

EditorWindow에서 Input 클래스는 안먹히는가 보다.

(참조 : http://answers.unity3d.com/questions/15067/input-in-editor-scripts.html)

그래서 대신 사용하는 게 Event 클래스..



Event


A UnityGUI event.

Events correspond to user input (key presses, mouse actions), or are UnityGUI layout or rendering events.

For each event OnGUI is called in the scripts; so OnGUI is potentially called multiple times per frame. Event.current corresponds to "current" event inside OnGUI call.

See Also: GUI Scripting Guide, EventType.

Variables
rawType

type

The type of event.

mousePosition

The mouse position.

delta

The relative movement of the mouse compared to last event.

button

Which mouse button was pressed.

modifiers

Which modifier keys are held down.

clickCount

How many consecutive mouse clicks have we received.

character

The character typed.

commandName

The name of an ExecuteCommand or ValidateCommand Event.

keyCode

The raw key code for keyboard events.

shift

Is Shift held down? (Read Only)

control

Is Control key held down? (Read Only)

alt

Is Alt/Option key held down? (Read Only)

command

Is Command/Windows key held down? (Read Only)

capsLock

Is Caps Lock on? (Read Only)

numeric

Is the current keypress on the numeric keyboard? (Read Only)

functionKey

Is the current keypress a function key? (Read Only)

isKey

Is this event a keyboard event? (Read Only)

isMouse

Is this event a mouse event? (Read Only)

Functions
GetTypeForControl

Use

Use this event.

Class Variables
current

The current event that's being processed right now.

Class Functions
KeyboardEvent

Create a keyboard event.



링크 : http://docs.unity3d.com/Documentation/ScriptReference/Event.html

반응형

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

유니티 소소한 TIP  (0) 2013.04.05
How to get SceneView Camera?  (0) 2013.03.25
비활성화 된 오브젝트 찾을 때..  (0) 2013.03.21
iOS 60프레임으로 셋팅하기  (0) 2013.03.08
씬 로딩화면  (0) 2013.03.08
Posted by blueasa
, |

비활성화 된 오브젝트를 찾을 때..

몰랐었는데 transform.FindChild() 함수가 자기 자식의 비활성 오브젝트까지 검사한다.

유용하게 쓸 것 같다.

(근데 왜 레퍼런스에는 FindChild() 함수가 안보이지..? -_-;)


1) 상위에 활성화 된 GameObject가 필요.

2) 활성화 된 상위 GameObject에서 GameObject.transform.FindChild() 함수로 비활성화 된 GameObject를 찾는다.


예) 

1 GameObject goParent; 2 Transform trInactiveObject = goParent.transform.FindChild("찾고 싶은 비활성화 된 오브젝트 이름"); 3 trInactiveObject.gameObject.SetActive(true); // 비활성 오브젝트 활성화




참조 : http://devkorea.co.kr/bbs/board.php?bo_table=m03_qna&wr_id=26759&sca=UNITY&sfl=wr_subject%7C%7Cwr_content&stx=%EB%B9%84%ED%99%9C%EC%84%B1&sop=and&currentId=44


--------------------------------------------------------------------------------------------------------


Transform.childCount;    // 바로 아래의 자식 개수(비활성화 된 자식 포함)를 반환

Transform.GetChild(int index);    // 해당 index의 자식 Transform(비활성화 된 자식 포함)을 반환

반응형

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

How to get SceneView Camera?  (0) 2013.03.25
EditorWindow에서 마우스/키보드 입력 체크  (2) 2013.03.22
iOS 60프레임으로 셋팅하기  (0) 2013.03.08
씬 로딩화면  (0) 2013.03.08
Change MonoDevelop Line Ending  (0) 2013.03.06
Posted by blueasa
, |

Unity Singleton

Unity3D/Script / 2013. 3. 11. 10:58

Example :

GameMaster.cs

public class GameMaster : MonoSingleton< GameMaster >
{
    public int difficulty = 0;
    public override void Init(){ difficulty = 5; }
}

OtherClass.cs

You forgot a "using UnityEngine;" fixed. :P

using UnityEngine;
public class OtherClass: MonoBehaviour
{
    void Start(){ print( GameMaster.instance.difficulty ); } // 5
}

The code :

using UnityEngine;
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    private static T m_Instance = null;
    public static T instance
    {
        get
        {
            // Instance requiered for the first time, we look for it
            if( m_Instance == null )
            {
                m_Instance = GameObject.FindObjectOfType(typeof(T)) as T;
 
                // Object not found, we create a temporary one
                if( m_Instance == null )
                {
                    Debug.LogWarning("No instance of " + typeof(T).ToString() + ", a temporary one is created.");
                    m_Instance = new GameObject("Temp Instance of " + typeof(T).ToString(), typeof(T)).GetComponent<T>();
 
                    // Problem during the creation, this should not happen
                    if( m_Instance == null )
                    {
                        Debug.LogError("Problem during the creation of " + typeof(T).ToString());
                    }
                }
                m_Instance.Init();
            }
            return m_Instance;
        }
    }
    // If no other monobehaviour request the instance in an awake function
    // executing before this one, no need to search the object.
    private void Awake()
    {
        if( m_Instance == null )
        {
            m_Instance = this as T;
            m_Instance.Init();
        }
    }
 
    // This function is called when the instance is used the first time
    // Put all the initializations you need here, as you would do in Awake
    public virtual void Init(){}
 
    // Make sure the instance isn't referenced anymore when the user quit, just in case.
    private void OnApplicationQuit()
    {
        m_Instance = null;
    }
}


출처 : http://wiki.unity3d.com/index.php/Singleton

반응형
Posted by blueasa
, |

원하는 프레임 속도를 설정하기 위해 Unity iOS 에 의해 생성되는 사용자의 XCode 프로젝트를 열고AppController.mm 파일을 선택합니다.

#define kFPS 30


...위의 라인이 현재의 프레임 속도를 결정합니다. 그러면 사용자는 원하는 값을 설정하기 위해 변화만 주면 됩니다. 예를 들어, define 을:-


#define kFPS 60


...위와 같이 바꾼 경우 어플리케이션이 30 FPS 대신에 60 FPS 로 랜더링 것입니다.


출처 : http://unitykoreawiki.com/index.php?n=KrMain.iphone-Optimizing-MainLoop

반응형
Posted by blueasa
, |

씬 로딩화면

Unity3D/Tips / 2013. 3. 8. 14:34

Unity Pro only


AsyncOperation async = Application.LoadLevelAsync( 씬넘버 ); 

while( !async.isDone ) 
{

    // async.progress 참조해서 로딩 게이지 출력
}


Application.LoadLevelAsync로 비동기 씬 로딩을 할 수 있구요 
- 로딩이 다 되었는지는 
async.isDone 
- 얼마나 진행이 되었는지는 
async.progress 



참조1 : http://devkorea.co.kr/bbs/board.php?bo_table=m03_qna&wr_id=25581&sca=UNITY&sfl=wr_subject%7C%7Cwr_content&stx=%EB%A1%9C%EB%94%A9%ED%99%94%EB%A9%B4&sop=and&currentId=44


참조2 : http://docs.unity3d.com/Documentation/ScriptReference/Application.LoadLevelAsync.html

반응형
Posted by blueasa
, |

Project-Solution Options-Source Code-C# Source Code-Line Endings

(need UnChecked 'Use default settings from 'Text file')


1) 


2)


3)


반응형
Posted by blueasa
, |

Raycast

Unity3D/Physics / 2013. 2. 28. 18:50

static function Raycast (ray : Ray, out hitInfo : RaycastHit, distance : float = Mathf.Infinity, layerMask : int = kDefaultRaycastLayers) : boolean


Parameters

rayThe starting point and direction of the ray.
distanceThe length of the ray
hitInfoIf true is returned, hitInfo will contain more information about where the collider was hit (See Also:RaycastHit).
layerMaskLayer mask that is used to selectively ignore colliders when casting a ray.

Returns

boolean - True when the ray intersects any collider, otherwise false.

Description

Same as above using ray.origin and ray.direction instead of origin and direction.

참조1 : http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html


위는 많이 사용되는 RayCast() 함수이다.

여기서 이야기 할 것은 4번째 매개변수인 Layer mask이다.

처음엔 레퍼런스를 대충 봐서 충돌을 무시할 Layer mask 인 줄 알았지만 그 반대였다.

충돌을 체크하고 싶은 Layer mask를 넣어야 한다.

Layer mask 사용방법에 대해서는 아래 참조2에 나온다.

참조2 : http://docs.unity3d.com/Documentation/Components/Layers.html


기본적으로 아래와 같이 사용하면 된다.

ex1)

1 int layerMask = (-1) - (1 << LayerMask.NameToLayer("Player")); // Everything에서 Player 레이어만 제외하고 충돌 체크함 2 Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), hit, Mathf.Infinity, layerMask);


ex2)

1 int layerMask = (-1) - (1 << LayerMask.NameToLayer("Player")); 2 RaycastHit hit; 3 Ray ray = Camera.mainCamera.ScreenPointToRay( screenPos ); // screenPos는 화면상 클릭 좌표 4 bool result = Physics.Raycast( ray, out hit, Mathf.Infinity, layerMask );


ex3) 

1 int layerMask = 1 << LayerMask.NameToLayer("Player"); // ignore LayerMask 2 layerMask = ~layerMask ; // Invert LayerMask 3 RaycastHit hit; 4 Ray ray = Camera.mainCamera.ScreenPointToRay( screenPos ); // screenPos는 화면상 클릭 좌표 5 bool result = Physics.Raycast( ray, out hit, Mathf.Infinity, layerMask );


ex4)  // 추가

1 int layerMask = (1 << LayerMask.NameToLayer("Player")) + (1 << LayerMask.NameToLayer("Mob")); // ignore LayerMask(Player와 Mob 레이어 체크 무시하기 위해..)

2 layerMask = ~layerMask ; // Invert LayerMask 3 RaycastHit hit; 4 Ray ray = Camera.mainCamera.ScreenPointToRay( screenPos ); // screenPos는 화면상 클릭 좌표 5 bool result = Physics.Raycast( ray, out hit, Mathf.Infinity, layerMask );


참조2의 맨아래 보면 보면 ex3)과 같은 방식으로 사용된 걸 볼 수 있다.

충돌 제외할 Layer Mask를 설정 한 후 ~ 연산자로 Invert 시키고 있다.

처음엔 위쪽만 대충 읽어서 그냥 무시할 Layer Mask를 넣는 줄 알고 했다가 안돼서 레퍼런스가 틀린 줄 알았는데..

제대로 써있다..;;

레퍼런스도 끝까지 정독해야 된다는 걸 느끼게 해줬다..;;

가능하면 ex3) 방식으로 사용을 하자.


[추가]

여러 레이어를 제어하는 부분이 빠진 것 같아서 ex4)를 추가..


P.s. Everything Layer = -1

P.s.2. LayerName을 int로 변환할 때는 LayerMask.NameToLayer 를 사용하면 된다.

반응형

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

오브젝트 간 충돌을 막고 싶을 때..  (0) 2012.11.05
Posted by blueasa
, |

[참조 글 및 참조파일]

Link :http://forum.unity3d.com/threads/165254-Unity-4-dynamic-font-support-for-NGUI 

File : 

NGUI_277c_DynamicFonts_and_Readme.zip


※ 파일명과 readme에는 NGUI 2.7.7이라고 돼 있지만 정황상 NGUI 2.2.7을 오표기 한 것 같다.


[NGUI 2.3.4 대응되는 수정 파일]

File : 

NGUI 2.3.4_DynamicFont_Source.zip



[사용기]

※ 현재 사용하려니 NGUI 2.3.4 버전이다. 위의 파일과 UIFont.cs가 좀 달라서 직접 수정해야 했다.


1) NGUI 2.3.4 버전에 맞춘다.


2) 위의 파일(NGUI 2.3.4_DynamicFont_Source.zip)을 받아서 풀어보면, UIFont.cs, UIFontInspector.cs 두 파일이 있다.

    각각 해당위치에 덮어씌우자.

   (주의: 덮어씌우면 기존 폰트 프리팹의 UIFont 스크립트가 missing이 될 수 있다. 바뀐 UIFont를 다시 넣어주면 정상 작동한다.)


3) 원하는 TTF 폰트 파일을 프로젝트에 올린다.(테스트용으로 Windows\Fonts\에 있는 '맑은고딕'을 사용했음.)

    올리면 아래와같이 자동으로 다이나믹 폰트로 생성되면서 Material과 텍스쳐가 생성된다.

    인스펙터 창에서는 폰트 사이즈 등을 조절할 수 있다.



3) Empty GameObject를 하나 생성한다.



4) 이름을 원하는대로 바꾼다.(임의로 MyDynamicFont로 바꿈)



5) UIFont 스크립트를 추가한다.



6) Font Type을 Dynamic으로 바꾸고,

    6-1) Font : 원하는 폰트(임의로 MALGUN 넣음)를 넣는다.

    6-2) Material : MALGUN 아래 있는 Material(스샷에서는 Font Material)을 드래그해서 넣는다.

          ※ 위 참조 데이터의 readme에서는 Material을 새로 만드는 데, 폰트 아래 있는걸 사용해도 별 차이가 없어서 그냥 쓰는걸로 설명함.. 왜 새로 만드는 지 모르겠음. 차후 문제가 생긴다면 수정해야 될 듯.

    6-3) Size : 3)에서 본 Size(스샷에서는 16)를 넣어준다.(이 부분은 좀 더 확인을 해 봐야겠다)

          ※ 여기서의 사이즈는 폰트 사이즈와 매칭이 돼야 Height가 제대로 맞는 것 같다. 폰트 사이즈를 키우려면 3)의 사이즈부터 수정 후 다시 매칭 시키자.



7) 만든 MyDynamicFont를 Prefab으로 만들자.(폰트 만들기는 완료)



8) 'NGUI-Create a Widget'을 눌러서 Widget Tool을 열고, Font 란에 7)에서 만든 MyDynamicFont Prefab을 넣는다.



9) Label을 하나 만든다.(Add To)

    제대로 MyDynamicFont를 써서 'New Label'이 뜬 걸 볼 수 있다.



10) 테스트로 한글/영어/한자/숫자/특수문자 등을 맘대로 넣어봤다. 잘된다.



11) 추가로.. 이제껏 쓴 글이 텍스쳐에 찍혀있는 걸 볼 수 있다.

     글자수가 늘어나서 텍스쳐를 다 채울정도가 되면 텍스쳐 사이즈가 자동으로 늘어난다.




P.s. Dynamic Font가 BM Font보다 Draw Call이 높다고 들었는데..

       잠시 테스트 해봐서는 폰트 하나당 Draw Call이 1이다(BMF랑 같음).

       어떤 경우에 늘어나는 지 모르겠다.(아시는 분 가르쳐 주세요..=_=;)

반응형
Posted by blueasa
, |

1) NavMesh Layer 셋팅 방법..




2) NavMesh Layer 셋팅 후 Bake 하는 방법

   (링크 : http://docs.unity3d.com/Documentation/Components/class-NavMeshLayers.html)


NavMesh Layers (Pro only)

The primary task of the navigation system is finding the optimal path between two points in navigation-space. In the simplest case, the optimal path is the shortest path. However, in many complex environments, some areas are harder to move thru than others (for example, crossing a river can be more costly than running across a bridge). To model this, Unity utilizes the concept of cost and the optimal path is defined as the path with the lowest cost. To manage costs, Unity has the concept of Navmesh Layers. Each geometry marked up as Navmesh Static will belong to a Navmesh Layer.

During pathfinding, instead of comparing lengths of potential path segments, the cost of each segment is evaluated. This is a done by scaling the length of each segment by the cost of the navmesh layer for that particular segment. Note that when all costs are set to 1, the optimal path is equivalent to the shortest path.

To define custom layers per project

  • Go to Edit->Project Settings->Navmesh Layers
  • Go to one of the user layers, and set up name and cost
    • The name is what will be used everywhere in the scene for identifying the navmesh layer
    • The cost indicates how difficult it is to traverse the NavMesh layer. 1 is default, 2.0 is twice as difficult, 0.5 is half as difficult, etc.
  • There are 3 built-in layers
    • Default - specifies the cost for everything not otherwise specified
    • Not walkable - the cost is ignored
    • Jump - the cost of automatically generated off-mesh links

To apply custom layers to specific geometry

  • Select the geometry in the editor
  • Pull up the Navigation Mesh window (Window->Navigation)
  • Go to the Object tab, and select the desired Navigation layer for that object
  • If you have Show NavMesh enabled in the Navmesh Display window, the different layers should show up in different colors in the editor.

To tell an agent what layers he can or cannot traverse

  • Go to the NavMeshAgent component of the agent's geometry
  • Modify NavMesh Walkable property
  • Don't forget to set the agent's destination property from a script

Note: Setting the cost value below 1 is not recommended, as the underlying pathfinding method does not guarantee an optimal path in this case

One good use case for using Navmesh Layers is:

  • You have a road that pedestrians (NavmeshAgents) need to cross.
  • The pedestrian walkway in the middle is the preferred place for them to go
  • Set up a navmesh layer with high cost for most of the road, and a navmesh layer with a low cost for the pedestrian walkway.
  • This will cause agents to prefer paths that go thru the pedestrian walkway.

Another relevant topic for advanced pathfinding is Off-mesh links 


반응형
Posted by blueasa
, |

유니티 4.0을 설치하고 실행하면, 위와 같이 “Error loading page Couldn’t read a file:// file”이라고 나오면서 실행이 안 될 때가 있습니다. 이 문제의 원인은 한글로 된 운영체제 계정 폴더 때문인 것 같습니다. 이 문제를 해결하려면, 영어로 계정을 만들어서 실행하면 됩니다. 그리고 라이센스 처리 과정이 끝나고 나면, 다시 한글 계정으로 실행해도 됩니다.


출처 : http://sunhyeon.wordpress.com/2012/11/21/%EC%9C%A0%EB%8B%88%ED%8B%B0-4-%EC%84%A4%EC%B9%98-%ED%9B%84-%EC%8B%A4%ED%96%89-%EC%98%A4%EB%A5%98-%ED%95%B4%EA%B2%B0%ED%95%98%EA%B8%B0/


반응형

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

씬 로딩화면  (0) 2013.03.08
Change MonoDevelop Line Ending  (0) 2013.03.06
Unity 4.x에서 이전 애니메이션 방식 사용할 때..  (0) 2013.02.06
스크립트 로딩 순서 정하는 방법  (0) 2013.02.06
Unity3d 50가지 팁  (0) 2013.02.05
Posted by blueasa
, |