2022년 10월 7일 금요일

Game Event (Unity,ScriptableObject)

 


https://drive.google.com/file/d/1wYwdK6P3bS1nzN_WYtdIq2Bg0gGmYY1o/view?usp=sharing


################### 간단한 INVOKE 코드
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class ClickTheMinimap : MonoBehaviour,IPointerClickHandler
{

    [SerializeField] GameEvent _onClickMinimap;

    public void OnPointerClick(PointerEventData eventData)
    {
        _onClickMinimap.Invoke();
    }

}

################### 간단한 INVOKE 코드










################### 스크립터블 오브젝트
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


[CreateAssetMenu(menuName ="Game Event",fileName="new Game Event")]
public class GameEvent : ScriptableObject
{

    /// <summary>
    /// HashSet 을 사용하면 중복을 피할수 있다
    /// </summary>
    HashSet<GameEventListener> _listeners = new HashSet<GameEventListener>();
    // Start is called before the first frame update
    public void Invoke()
    {
        foreach (var globalEventListener in _listeners)
            globalEventListener.RaiseEvent();
    }

    public void Register(GameEventListener gameEventListener) => _listeners.Add(gameEventListener);

    public void DeRegister(GameEventListener gameEventListener) => _listeners.Remove(gameEventListener);
}

################### 스크립터블 오브젝트





################### GameEventListener
using UnityEngine;
using UnityEngine.Events;

public class GameEventListener : MonoBehaviour
{
    [SerializeField] protected GameEvent _gameEvent;
    [SerializeField] protected UnityEvent _unityEvent;


    private void Awake()
    {
        _gameEvent.Register(gameEventListener: this);

    }
    private void OnDestroy()
    {
        _gameEvent.DeRegister(gameEventListener: this);
    }

    public virtual void RaiseEvent() => _unityEvent.Invoke();
}

################### GameEventListener





################### GameEventListener 변형버전

using System.Collections;
using UnityEngine;
using UnityEngine.Events ;

public class GameEventListenerWithDelay : GameEventListener
{

    [SerializeField] float _delay = 1f;
    [SerializeField] UnityEvent _delayedUnityEvent;

    public override void RaiseEvent()
    {
        _unityEvent.Invoke();
        StartCoroutine(RunDelayedEvent());
    }

    IEnumerator RunDelayedEvent()
    {
        yield return new WaitForSeconds(_delay);
        _delayedUnityEvent.Invoke();
    }

}

################### GameEventListener 변형버전






   GameEvent 생성 -> 스크립터블 오브젝트라 생성해놓고 사용하면 된다.





EventListner 등록해놓고 원하는 GameEvent를 등록


invoke하면 

각자 등록된 UnityEvent를 실행







댓글 없음:

댓글 쓰기

git rejected error(feat. cherry-pick)

 문제 아무 생각 없이 pull을 받지않고 로컬에서 작업! 커밋, 푸시 진행을 해버렷다. push에선 remote와 다르니 당연히 pull을 진행해라고 하지만 로컬에서 작업한 내용을 백업하지 않고 진행하기에는 부담스럽다(로컬작업 유실 가능성) 해결하려...