유니티
[C#] Action, Func
simstealer
2022. 9. 29. 17:08
Action
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
// ###############################################
// NAME : Simstealer
// MAIL : minsub4400@gmail.com
// ###############################################
// Action 테스트 스크립트
public class SMS_ActionTest : MonoBehaviour
{
// Action은 반환값이 없는 대리자다.
// 반환값이 없는 함수를 등록한다.
Action testAction;
//***** 다른 스크립트에서 여기에 있는 함수를 가져다 쓰려할 경우 다음과 같이 선언한다.
// public static Action testAction;
// 다른 스크립트에서는 이렇게 쓴다. SMS_ActionTest.testAction(); orSMS_ActionTest.Invoke();
// Func도 마찬가지로 사용가능하다.
// int형의 매개변수를 받는 경우
Action<int> testAction2;
private void Start()
{
testAction += A;
testAction += B;
testAction += C;
testAction.Invoke();
// 함수가 등록되어있는 것이 없는 경우에는 실행되지 않는다.
// testAction?.Invoke();
}
void A() { Debug.Log("Action Test A"); }
void B() { Debug.Log("Action Test B"); }
void C() { Debug.Log("Action Test C"); }
}
Func
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
// ###############################################
// NAME : Simstealer
// MAIL : minsub4400@gmail.com
// ###############################################
// Func 테스트 스크립트
public class SMS_FuncTest : MonoBehaviour
{
// Func는 반환값이 있는 대리자이다.
// 그러므로 반환값이 있는 함수를 등록해야한다.
Func<bool> testFunc;
// 매개변수를 int, string 두개를 받고 반환을 bool로 할 경우
Func<int, string, bool> testFunc2;
private void Start()
{
testFunc += TrueFunction;
testFunc += FalseFunction;
testFunc.Invoke();
}
bool TrueFunction()
{
Debug.Log("Func Test True");
return true;
}
bool FalseFunction()
{
Debug.Log("Func Test False");
return false;
}
}