블로그 이미지
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-24 00:01

'WaitForSeconds'에 해당되는 글 2건

  1. 2012.11.21 특정시간 뒤에 함수 호출하도록 설정하기 (WaitForSeconds)
  2. 2012.11.21 WaitForSeconds()



 WaitForSeconds라는 메소드가 있는데 C#에서 쓰러면 조금 까다롭게 형식에 맞춰서 작성해줘야 한다.

위 예제와 같이 Awake라는 메소드에서 시간을 두번 출력할때 첫번째 시간을 출력 한 뒤 5초뒤에 두번째 시간을 출력하고자 하는경우 또는 일정시간마다 반복 재귀호출 되는 메소드를 작성하고 싶을때에
'IEnumerator' 라는 인터페이스를 사용하도록 해당 메소드 앞에 적어줘야 한다.

IEnumerator delayTime()
{
yield return new WaitForSeconds(1);
Debug.Log("time = " + Time.time );
}

 위와 같이 delayTime이라는 메소드를 적어주면 메소드가 호출되면 1를 기다렸다가 1초뒤에 Debug 문장이 실행된다.

IEnumerator 인터페이스를 사용하는 메소드를 실행하기 위해서는 
특정 호출 메소드를 이용해야 하는데
StartCoroutine(delayTime);

다른 메서드들 처럼 그냥 메서드명() 으로 호출하면 실행되지 않고 위와 같이 StartCoroutine(메서드명) 으로 호출해야 한다.


일정시간 간격으로 계속 반복되어 실행되는 메서드를 만들러면
void Start () {
        StartCoroutine(countTime, 1);
 }
  
    IEnumerator countTime(float delayTime)
    {
        Debug.Log("Time = " + Time.time);
        yield return new WaitForSeconds(delayTime);
        StartCoroutine( countTime, 1 );
    }

위와 같이 적어주면 countTime이 waitForSeconds 명령에 의해 일정시간 만큼 딜레이를 한 뒤 자기자신을 재 호출하게되어 
1초 간격으로 계속 반복 호출하도록 할 수 있다.


출처 : http://clack.tistory.com/50

반응형

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

폰트의 픽셀정보로 문자열을 Mesh들로 생성하여 보여주기  (0) 2012.11.24
Interpolate  (0) 2012.11.22
AnimationEvent 추가 방법  (0) 2012.11.21
WaitForSeconds()  (0) 2012.11.21
Attributes 설명 모음  (0) 2012.11.18
Posted by blueasa
, |

WaitForSeconds()

Unity3D/Script / 2012. 11. 21. 14:08

/* 유니티를 하면서 여기저기 해외 동영상 강좌도 보고 따라하고 있습니다만 그래도 자바스크립트보단 C#이 간지 있어 보이는거 같아서 C#으로 스크립트를 만들어 보고 있긴한데 어째 자바 스크립트 보단 많이 불편한거 같은 느낌이 드는건 나만의 착각일까요... 그 일례로 WaitForSeconds()함수를 사용하면서 삽질한걸 한번 끄적여 보겠습니다.*/


스크립트 레퍼런스에 나온 설명입니다.

static function WaitForSeconds (seconds : float) : WaitForSeconds

Description

Creates a yield instruction to wait for a given number of seconds

C#

using UnityEngine;

using System.Collections;


public class example : MonoBehaviour 

{

     public IEnumerator Awake() 

    {

          print(Time.time);

yield return new WaitForSeconds(5);
print(Time.time);

    }

}


근데 예제에 저런식으로 썼다가 개코피 터집니다 -ㅅ-;;; 한시간 정도 삽질했네요

구문은 맞는데 일반 함수를 그냥 사용할려고 하면 조금 변형을 가해줘야 됩니다.


public class myCreator : MonoBehaviour 

{

public GameObject box;

public bool readynow = false;


// Use this for initialization

void Start () 

{

}

// Update is called once per frame

void Update () 

{

if( readynow == true )

{

StartCoroutine( MakeBox() );

}

}

IEnumerator MakeBox()

{

readynow = false;

Instantiate( box, transform.position, transform.rotation );

yield return new WaitForSeconds(0.01f);

readynow = true;

}

}


보시면 아시겠지만 StartCoroutine()함수를 사용해서 해주어야 에러가 나질 않아요~

저거 찾는다고 아놔 -ㅅ-;

더불어서 StartCoroutine()함수 스크립트 메뉴얼도 보시겠습니다.

function StartCoroutine (routine : IEnumerator) : Coroutine

Description

Starts a coroutine.

The execution of a coroutine can be paused at any point using the yield statement. The yield return value specifies when the coroutine is resumed. Coroutines are excellent when modelling behaviour over several frames. Coroutines have virtually no performance overhead. StartCoroutine function always returns immediately, however you can yield the result. This will wait until the coroutine has finished execution.

When using JavaScript it is not necessary to use StartCoroutine, the compiler will do this for you. When writing C# code you must call StartCoroutine.

C#
using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
void Start() {
print("Starting " + Time.time);
StartCoroutine(WaitAndPrint(2.0F));
print("Before WaitAndPrint Finishes " + Time.time);
}
IEnumerator WaitAndPrint(float waitTime) {
yield return new WaitForSeconds(waitTime);
print("WaitAndPrint " + Time.time);
}
}

Another Example:
C#
using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
IEnumerator Start() {
print("Starting " + Time.time);
yield return StartCoroutine(WaitAndPrint(2.0F));
print("Done " + Time.time);
}
IEnumerator WaitAndPrint(float waitTime) {
yield return new WaitForSeconds(waitTime);
print("WaitAndPrint " + Time.time);
}
}

아... 줄 정리 해줄려니 귀찮아서 못해먹겠네요 이렇게 해주시면 WaitForSeconds()함수를 에러 없이 사용 하실수 있습니다.
마지막으로 Start함수나 Update함수에 그냥 사용을 가하실려면 이런식으로 해주시면 됩니다.

IEnumerator Start () 
{
int i = 0;
Vector3 pos = transform.position;
for( i = 0; i <= 3; ++i )
{
Instantiate( myPrefab, new Vector3( pos.x + i * distanceMultiplier, pos.y, pos.z ), transform.rotation );
yield return new WaitForSeconds(0.5f);
Debug.Log( "mode ball" + i );
}
}

Update쪽은 이런식으로 처리 되는지 안되는지 확인을 못해봤으니 그건 직접해보시길~~




반응형
Posted by blueasa
, |