=================================
=================================
=================================
C# 시간관련 https://202psj.tistory.com/1274?category=179380 |
=================================
=================================
=================================
출처: https://hyunity3d.tistory.com/367
특정 시간마다 호출되는 함수를 만들고 싶을수 있습니다.
using UnityEngine; using System.Collections; public class CsGameManager : MonoBehaviour { private float TimeLeft = 2.0f; private float nextTime = 0.0f; void MoveMoles() { print("moveMole!"); } void Update() { //2초마다 실행 if(Time.time > nextTime){ nextTime = Time.time + TimeLeft; MoveMoles(); } } |
유니티 내에 존재하는 함수도 있음아래 함수는 특정시간 후 함수 호출 (반복호출시 끝에 Invoke("MoveMoles", 2.0f)) 를 넣어주면 계속해서 반복호출이 되겠죠?
using UnityEngine;
using System.Collections;
public class CsGameManager : MonoBehaviour {
void Start()
{
Invoke("MoveMoles", 2.0f);
}
void MoveMoles()
{
print("moveMole!");
}
}
아래처럼 코루틴을 사용하는 방법이 제일 일반 적인 방법이 아닐까 싶습니다.
아래코드는 CountTime이 무한 반복 됩니다.
using UnitEngine;
using System.Collections;
public class Example : MonoBehaviour {
void Start() {
StartCoroutine(CountTime, 1);
}
IEnumerator CountTime(float delayTime) {
Debug.Log("Time : " + Time.time);
yield return new WaitForSeconds(delayTime);
StartCoroutine(CountTime, 1);
}
}
출처: https://hyunity3d.tistory.com/367 [Unity3D]
=================================
=================================
=================================
출처: http://davidknopp.net/code-samples/task-scheduler-c-unity/
using System;
using System.Collections.Generic;
using UnityEngine.Assertions;
namespace Gemini
{
public class TaskScheduler : IScheduledTask
{
#region public
public struct TaskRecord : IEquatable<TaskRecord>
{
public IScheduledTask m_task;
public uint m_frequency;
public int m_phase;
// implement IEquatable to avoid allocations for calls to List.Contains
public bool Equals( TaskRecord record )
{
return m_task == record.m_task &&
m_frequency == record.m_frequency &&
m_phase == record.m_phase;
}
public override bool Equals( object obj )
{
return Equals( ( TaskRecord )obj );
}
public override int GetHashCode()
{
return HashCode.Combine( m_task.GetHashCode(),
m_frequency.GetHashCode(),
m_phase.GetHashCode() );
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="phaseIterationCount">Number of frame iterations to look at when determining the optimum phase for a task</param>
public TaskScheduler( int phaseIterationCount )
{
m_tasks = new List<TaskRecord>();
m_frame = 0;
m_phaseIterationCount = phaseIterationCount;
}
public int TaskCount
{
get { return m_tasks.Count; }
}
public int Frame
{
get { return m_frame; }
}
/// <summary>
/// Registers the given task for scheduled updates
/// </summary>
/// <param name="task">The task to schedule</param>
/// <param name="frequency">The desired update frequency, in frames</param>
/// <param name="phase">An offset used to scatter tasks with similar frequencies</param>
public void AddTask( IScheduledTask task, uint frequency, int phase )
{
Assert.IsFalse( frequency == 0, string.Format( "TaskScheduler.AddTask: Frequency for task '{0}' must be greater than 0", task ) );
m_tasks.Add( new TaskRecord
{
m_task = task,
m_frequency = frequency,
m_phase = phase
} );
}
/// <summary>
/// Registers the given task for scheduled updates, with an automatic phase assignment
/// </summary>
/// <param name="task">The task to schedule</param>
/// <param name="frequency">The desired update frequency, in frames</param>
public void AddTask( IScheduledTask task, uint frequency )
{
Assert.IsFalse( frequency == 0, string.Format( "TaskScheduler.AddTask: Frequency for task '{0}' must be greater than 0", task ) );
AddTask( task, frequency, FindOptimumPhase() );
}
public void RemoveTask( IScheduledTask task )
{
int index = m_tasks.FindIndex( x => x.m_task == task );
Assert.IsTrue( index > 0, string.Format( "TaskScheduler.RemoveTask: Task '{0}' isn't registered with the scheduler", task ) );
if ( index > 0 )
{
m_tasks.RemoveAt( index );
}
}
public void ChangeFrequency( IScheduledTask task, uint frequency )
{
Assert.IsFalse( frequency == 0, string.Format( "TaskScheduler.ChangeFrequency: Frequency for task '{0}' must be greater than 0", task ) );
// remove and re-add task to recalculate phase
RemoveTask( task );
AddTask( task, frequency );
}
public void ScheduledTick()
{
for ( int i = 0; i < m_tasks.Count; i++ )
{
TaskRecord record = m_tasks[i];
if ( IsTaskScheduled( record, m_frame ) )
{
record.m_task.ScheduledTick();
}
}
++m_frame;
}
#endregion // public
#region private
private List<TaskRecord> m_tasks;
private int m_frame;
private int m_phaseIterationCount;
private bool IsTaskScheduled( TaskRecord record, int frame )
{
int offsetFrame = frame - record.m_phase;
return offsetFrame >= 0 &&
( offsetFrame % record.m_frequency ) == 0;
}
private int FindOptimumPhase()
{
int phase = 0;
int minTaskCount = int.MaxValue;
// look ahead to find frame with fewest running tasks
for ( int frame = m_frame; frame < m_phaseIterationCount; ++frame )
{
int frameTaskCount = 0;
// count number of tasks scheduled to run this frame
for ( int i = 0; i < m_tasks.Count; i++ )
{
if ( IsTaskScheduled( m_tasks[i], frame ) )
{
++frameTaskCount;
}
}
if ( frameTaskCount < minTaskCount )
{
minTaskCount = frameTaskCount;
phase = frame - m_frame;
}
}
return phase;
}
#endregion // private
}
}
=================================
=================================
=================================
기타관련링크
- https://docs.unity3d.com/kr/current/Manual/TimeFrameManagement.html
=================================
=================================
=================================
'프로그래밍 관련 > 언어들의 코딩들 C++ JAVA C# 등..' 카테고리의 다른 글
[C#] 난수, Random 관련 (0) | 2019.04.08 |
---|---|
[C#] struct 구조체 관련 (0) | 2019.04.07 |
[C#] C# 날짜, 시간 관련 (0) | 2019.04.06 |
[C#] 구조체, 기본변수형등등 에 null (Nullable<T> 타입) 사용하기 관련 (0) | 2019.04.01 |
[C#] c#에서 UnmanagedType의 종류 관련 (0) | 2019.04.01 |
댓글 영역