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

카테고리

분류 전체보기 (2737)
Unity3D (817)
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-19 00:04


[링크] http://dongin2009.blog.me/221131218231


반응형
Posted by blueasa
, |

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

NGUI의 이벤트 함수를 SendMessage로 호출하려고 함수 원형을 찾아보고 올려놓음.


UICamera sends out the following events to colliders:
  • OnHover (isOver) is sent when the mouse hovers over a collider or moves away.
  • OnPress (isDown) is sent when a mouse button gets pressed on the collider.
  • OnSelect (selected) is sent when a mouse button is first pressed on a game object. Repeated presses on the same object won't result in a new OnSelect.
  • OnClick () is sent with the same conditions as OnSelect, with the added check to see if the mouse has not moved much. UICamera.currentTouchID tells you which button was clicked.
  • OnDoubleClick () is sent when the click happens twice within a fourth of a second. UICamera.currentTouchID tells you which button was clicked.
  • OnDragStart () is sent to a game object under the touch just before the OnDrag() notifications begin.
  • OnDrag (delta) is sent to an object that's being dragged.
  • OnDragOver (draggedObject) is sent to a game object when another object is dragged over its area.
  • OnDragOut (draggedObject) is sent to a game object when another object is dragged out of its area.
  • OnDragEnd () is sent to a dragged object when the drag event finishes.
  • OnInput (text) is sent when typing (after selecting a collider by clicking on it).
  • OnTooltip (show) is sent when the mouse hovers over a collider for some time without moving.
  • OnScroll (float delta) is sent out when the mouse scroll wheel is moved.
  • OnKey (KeyCode key) is sent when keyboard or controller input is used.

To tap into them in your own custom scripts, simply create a script with the appropriate function, such as:
  1. void OnPress (bool isPressed)
  2. {
  3.     if (isPressed) Debug.Log("I was pressed on!");
  4.     else Debug.Log("I was unpressed");
  5. }

Pro-Tip #2

You can subscribe to events from any script using delegates: UICamera.onClick, UICamera.onHover, etc. These delegates will be called just before the actual notification gets sent to the proper object. You can use this functionality to listen in for events on a script regardless of whether they would be going to that script's game object or not.

Class Documentation

http://tasharen.com/ngui/docs/class_u_i_camera.html

If you have a question regarding this component or would like me to clarify something, just post a reply here.



출처 : http://www.tasharen.com/forum/index.php?topic=6711.0

반응형
Posted by blueasa
, |
부모 폼과 자식 폼이 있다; 자식 폼에서 A라는 버튼을 클릭했을 때; B라는 텍스트 박스의 내용을 부모 폼의 C라는 텍스트 박스에 표시하고 싶다; 그 방법은?

물론; 가장 간단한 방법은 private으로 선언되어 있는 C라는 텍트스 박스를 public으로 선언하고; 자식 폼에서 직접 이 텍스트 박스에 접근하여; 값을 대입하는 방법이 있습니다;

하지만; 개인적으로 이 방법은 C#이 지향하는 OOP(Object-oriented paradigm)를 위배하고; 깔끔하지 못한 방법으로 별로 권장하고 싶지 않네요;

개인적으로 권장하는 것은 이벤트(event)를 이용하는 것 입니다; 이벤트는 단순히 폼 간의 어떤 데이터를 주고 받을 수 있을 뿐만 아니라; 서로 다른 클래스 간의 데이터 전송에도 유용하며, 데이터를 구조체 형식으로도 넘길 수 있는 등 다양한 장점이 있지요; 무엇보다, OOP를 준수하면서도; 깔끔한 코드를 유지할 수 있다는 것에 후한 점수를 주고 싶군요;

이 이벤트를 구현하는 방법에 가장 핵심이 되는 내용은 바로 delegate 입니다.
C++/MFC, java 등 다른 언어에 능숙한 사람들 대부분이 C#에 금방 적응하게 됨에도 불구하고; 그나마 C#에서 가장 당황하는 개념이 delegate가 아닐까 싶네요; (나만 그런가?;)

delegate는 한글로 굳이 번역하자면; 대리자라고 하는데; C#이 다른 언어와 차별성을 가지는 중요한 몇 몇 이슈 중 하나가 이 녀석의 존재라고 생각합니다;

단어 뜻으로만 이해하자면; 어려우니까; 서두에 언급한 자식 폼에서 부모 폼으로 텍스트를 전달하는 예제를 통해; delegate의 역할을 이해해보죠;

이미 언급했지만; 자식 폼에서 부모 폼으로 데이터를 전달할 때, 이벤트를 이용하기로 하였는데; 이벤트에서 가장 기본적인 사실은; 이벤트를 발생하는 곳이 있으면, 이벤트를 받는 쪽도 있어야 된다는 것입니다;

따라서, 자식 폼에는 이벤트를 발생시키는 녀석을 정의하고, 부모 폼에서는 이벤트를 받는 녀석을 정의해야 된겠지요. 이미 C#을  이용해 윈 폼 프로그래밍을 해본 사람이라면; 폼에 버튼을 붙이고; 클릭 이벤트를 추가해서; 버튼을 클릭하면; 메시지 박스로 "Hello, World!" 정도는 경험이 있을 것 입니다;

이 때, 버튼도 우리가 예로 들려는 자식 폼과 같습니다; 버튼이 이벤트를 발생시키고, 부모 폼에서 버튼 이벤트를 받아, 거기서 메시지 박스를 띄운 것이기 때문이지요;

자 이벤트를 정의하는 과정은 다음과 같습니다;
사용자 삽입 이미지

클래스 ChildFormEventArgs는 이벤트 데이터가 들어 있는 클래스에 대한 기본 클래스인 EventArgs를 상속 받아 구현하였습니다. 우리는 자식 폼에서 부모 폼으로 텍스트를 전송할 목적이므로, 기본 클래스에 message란 속성을 추가하였구요;

그리고 그 아래 이벤트 대리자(delegate)를 선언하는데, 대리자를 통해 넘기는 파라미터에 주목해봅시다;
ChildFormEventArgs는 앞에 언급한대로 이벤트 데이터 이고, object sender는 뭘까요?

이벤트를 발생 시킨 주체입니다; 우리의 예에서는 바로 자식폼이 되겠지요;

이벤트를 위한 대리자를 선언했으면; 자식 폼에 이 이벤트를 발생시키기 위한 코드를 구현해야 합니다;
사용자 삽입 이미지

이벤트 선언부를 눈여겨 보세요;

이에 앞서 선언한 delegate에 이벤트를 위한 엑세스 한정자인 event를 붙였습니다; 그리고 파생 클래스에서 이 이벤트를 일으키거나 override 할 수 있도록 protected와 virtual 키워드를 붙였지요;

그리고 그 아래 정의된 메소드는 자식 폼에 추가한 버튼을 클릭하면 호출되는 녀석; 이미 알고 있듯이; 우리는 버튼을 클릭했을 때, 자식 폼에 있는 텍스트 박스(txtSentMessage)에 적힌 텍스트를 부모 폼에 전달하기 위함이므로; 앞서 정의한 event를 발생시킬 수 있는 NotifyEvent를 호출하도록 하였습니다;

그럼, 이제 부모 폼에서 이벤트를 받을 수 있도록 구현해보죠;
사용자 삽입 이미지

부모 폼의 생성자(constructor)에 자식폼의 메모리를 할당하고; 이벤트를 받기 위해 OnNotifyParent이벤트 핸들러를 추가합니다;

자, 여기서 대리자(delegate)의 역할을 이해할 수 있습니다. 자식 폼에서는 결코 부모 폼의 child_OnNotifyParent 메소드를 직접적으로 호출하지 않습니다. 단지, 이벤트로 정의한 OnNotifyParent(delegate)를 구현하였고; 이를 이용해 이벤트를 발생시키는 NotifyEvent 메소드만 구현했을 뿐이지요; 하지만 OnNotifyParent는 대리자란 명칭에 걸맞게; NotifyEvent가 호출되면; 간접적으로 child_OnNotifyParent 해줬습니다;

이 때 이벤트 데이터를 전달해주는 ChildFormEventArgs를 통해 자식폼의 텍스트 박스에 적힌 텍스트를 가져올 수 있네요;

다시, 정리하자면 이렇습니다.
1. 이벤트는 이벤트를 발생시키는 곳이 있으면, 발생한 이벤트를 듣는 곳도 있다;
2. 이벤트는 이벤트를 발생시키는 곳과 발생한 이벤트를 듣는 곳을 잇기 위한 대리자(delegate)로 구현한다.

delegate란 개념은 단지; 이벤트를 구현할 때만 쓰이지 않습니다; 제가 오래 전에 블로그에 쓴 C#에서 크로스 쓰레드 문제에서도 언급된 적이 있습니다. 사실 저도 저 때 delegate 개념이 구체화 되지는 않았습니다; 어렴풋이 이해만 했었고; 단지 저런 상황이 생기면; 다시 써먹기 위해 남겼을 뿐이지요..;

혹시나 필요하신 분들이 있을까; 아티클에 설명한 예제의 소스 코드를 첨부합니다;



반응형
Posted by blueasa
, |

내개만든 객체를 다른 객체에 이벤트를 사용하게 하기 위해서는 6가지로 나누어 볼수 있읍니다..

 

 이벤트를 발생시키는 객체서는4가지입니다

 이중 1,2는 매개 변수가 없을때 기본생성자를 사용함으로 생락 가능

 

 구독에서는 5,6번으로 폼 이벤트 사용할때 주로 사용을 많이 해봤을것으로 압니다

 

 

 이해 안되면  매개 변수가 있으면 구독 4가지,없으면 2가지 그냥 외우면 됩니다..

그리고 나만의 예제 하나 만들어 보면 모든데 이해 될것으로 생각 됩니다.

 

  

이벤트 사용하기

1.    새로운 데이터 타입 생성 [생락가능]

매개 변수가 없는 이벤트를 생성시 기본 생성자 public delegate void EventHandler(object sender, EventArgs e)를 사용하면 됨으로 생략 ,여기서는 minEventHandler라는 새로은 데이터 타입

public delegate void minEventHandler(object sender,minEventTestArgs e);//델리게이트 선언

 

2. 이벤트 매개 변수를 위한 객체 생성 [생락가능]

     1번의 두 번째 매개 변수에 사용하기 위한 객체로서 매개 변수로 넘길 데이터가 없으면 그냥 EventArg를 사용해도 됨.

public class minEventTestArgs : EventArgs

        {

        public DateTime m_Timer{get;set;}

        public minEventTestArgs(DateTime Timer)

        {

            this.m_Timer = Timer;

        }

  

3. 이벤트 정의 a 1번의 인터페이스

public event minEventHandler minEventTest;  // 이벤트 정의

 

4. 이벤트 발생

public void OnMinEventTest(minEventTestArgs e)  // 이벤트 발생 구독자에게 통보

        {

            if (minEventTest != null)

                minEventTest(this, e);

 }

 

 

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

5. 이벤트 핸들러 메소드

minTimer min;  //       

  private void Form1_Load(object sender, EventArgs e)

  {

            min = new minTimer();

            min.minEventTest += new minEventHandler(min_minEventTest);

 }

 

6. 이벤트 구독

Void min_minEventTest(object sender, minEventTestArgs e)

       {

            textBox1.Text = e.m_Timer.ToLongTimeString();

       }

 

 

=========================================================================================== 

여기서 부터 는  예제

1 minTimer라는 객체를 하나 만들고

이 객체는 1초마다 현재 시간을 알려주는 이벤트를 생성한는일을 함.

2 폼 에서는 minTimer객체 인터페이스를 만들고 이벤트를 구독한다

 

using System;

namespace WindowsFormsApplication1

{  

    public delegate void minEventHandler(object sender,minEventTestArgs e); //새로운 객체

    public class minTimer

    {

        System.Windows.Forms.Timer timer;               //시간을 읽어오는 타이머

      

        public event minEventHandler minEventTest;         //[2] 이벤트 정의

        public void OnMinEventTest(minEventTestArgs e)  //[3] 이벤트 발생 구독자에게 통보

        {

            if (minEventTest != null)

                minEventTest(this, e);

        }

 

        //

        public minTimer()

        {

            timer = new System.Windows.Forms.Timer();

            timer.Interval = 1000;

            timer.Enabled = true;

            timer.Start();

            timer.Tick += new EventHandler(timer_Tick);

        }

 

        //

        void timer_Tick(object sender, EventArgs e)

        {

            DateTime curTime = DateTime.Now;

            minEventTestArgs args = new minEventTestArgs(curTime);

            OnMinEventTest(args);

        }

    }

 

    // [1] 이벤트 인자를 위한 객체

    public class minEventTestArgs : EventArgs

    {

        public DateTime m_Timer{get;set;}

        public minEventTestArgs(DateTime Timer)

        {

            this.m_Timer = Timer;

        }

    }

}

 

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

폼에서

minTimer min; //       

        private void Form1_Load(object sender, EventArgs e)

        {

            min = new minTimer();

            min.minEventTest += new EventHandler(min_minEventTest);

         }

 

        void min_minEventTest(object sender, minEventTestArgs e)

        {

            textBox1.Text = e.m_Timer.ToLongTimeString();

        }

 

 

 

잘못된부분 있으면 정보 공유 차원에서라도

답글 부탁 합니다,


출처 : http://www.devpia.com/MAEUL/Contents/Detail.aspx?BoardID=18&MAEULNO=8&no=1831&page=4

반응형

'Programming > C#' 카테고리의 다른 글

interface(C# 참조)  (0) 2010.09.14
abstract(C# 참조)  (0) 2010.09.14
STL map == C# Dictionary  (0) 2010.09.13
자동 업데이트 프로그램  (1) 2010.09.10
간단한 자동 업데이트 프로그램 구현  (0) 2010.09.10
Posted by blueasa
, |

Custom Control 등을 구현 할 때 많이 사용되는 사용자 정의 이벤트를 만드는 법을 간단하게 정리 해봤습니다.

1. 핸들러 타입 정의

  이벤트 핸들러 타입을 정의 합니다. 필요에 따라 전달 값을 정의하면 됩니다.
  혹은 이미 .NET Framework에 정의된 핸들러를 사용해도 됩니다.

#region [컨트롤 이벤트 정의]
/// Boolean 값을 전달하는 Event Handler 
public delegate void wizEventHandlerBool(bool checkState);
/// 실행 상태가 변경 되었을 때 발생
public event wizEventHandlerBool StateChanged;
#endregion
 

2. 컨트롤에서 사용될 이벤트 전달 함수를 구현

  컨트롤 내부에서 이벤트를 처리 할 함수를 생성합니다.
  해당 델리케이트로 이벤트가 선언되어있는지 체크 후 이벤트를 발생 시킵니다.

#region [컨트롤 이벤트 구현][OnStateChanged]
/// 페이지 변경 이벤트
protected void OnStateChanged()
{ if(StateChanged != null) { StateChanged(this.cIsRun.Checked); } }
#endregion
 

3. 이벤트를 발생시킬 곳에서 이벤트 전달 함수를 호출

  필요한 곳에서 정의한 이벤트 전달 함수를 호출 하면 됩니다.
  예제에서는 체크박스의 상태가 변경된 경우 해당 이벤트를 발생시키도록 구현했습니다.


#region [Event][cIsRun_CheckedChanged]
private void cIsRun_CheckedChanged(object sender, EventArgs e)
{
	OnStateChanged();
}
#endregion
 
나머지는 일반 컨트롤에서 이벤트 처리 함수를 구현하는 방법과 동일 합니다.


출처 : http://wiz.pe.kr/180
반응형
Posted by blueasa
, |