How to create an array of event actions [duplicate] - c#

This question already has answers here:
array of events in C#?
(4 answers)
Closed 1 year ago.
I'm creating a touch manager, which fires Began and Ended events and other monobehaviours can subscribe to them. For some reason I am unable to find any information on creating a list of events actions.
This is an illustration of what I currently have:
public class TouchHandler : MonoBehaviour {
private static readonly int MAX_TOUCH_COUNT = 2;
public event Action<int> Began;
public event Action<int> Ended;
private void Update() {
if (Input.touchCount > 0) {
Touch[] touches = Input.touches;
int touchCount = Mathf.Min(touches.Length, MAX_TOUCH_COUNT);
for (int i = 0; i < touchCount; i++) {
Touch t = touches[i];
if (t.phase == TouchPhase.Began)
Began?.Invoke(i);
else if (t.phase == TouchPhase.Ended)
Ended?.Invoke(i);
}
}
}
}
public class Listener : MonoBehaviour {
[SerializeField] private TouchHandler th;
private int touchIndexToListen = 0;
private void OnEnable() {
th.Began += TouchBegan;
th.Ended += TouchEnded;
}
private void OnDisable() {
th.Began -= TouchBegan;
th.Ended -= TouchEnded;
}
private void TouchBegan(int index) {
if (index != touchIndexToListen)
return;
Debug.Log("TouchBegan");
}
private void TouchEnded(int index) {
if (index != touchIndexToListen)
return;
Debug.Log("TouchEnded");
}
}
This is how I'd want it to work:
public class TouchHandler : MonoBehaviour {
private static readonly int MAX_TOUCH_COUNT = 2;
public event Action[] Began = new Action[MAX_TOUCH_COUNT];
public event Action[] Ended = new Action[MAX_TOUCH_COUNT];
private void Update() {
if (Input.touchCount > 0) {
Touch[] touches = Input.touches;
int touchCount = Mathf.Min(touches.Length, MAX_TOUCH_COUNT);
for (int i = 0; i < touchCount; i++) {
Touch t = touches[i];
if (t.phase == TouchPhase.Began)
Began[i]?.Invoke();
else if (t.phase == TouchPhase.Ended)
Ended[i]?.Invoke();
}
}
}
}
public class Listener : MonoBehaviour {
[SerializeField] private TouchHandler th;
private int touchIndexToListen = 0;
private void OnEnable() {
th.Began[touchIndexToListen] += TouchBegan;
th.Ended[touchIndexToListen] += TouchEnded;
}
private void OnDisable() {
th.Began[touchIndexToListen] -= TouchBegan;
th.Ended[touchIndexToListen] -= TouchEnded;
}
private void TouchBegan(int index) {
Debug.Log("TouchBegan");
}
private void TouchEnded(int index) {
Debug.Log("TouchEnded");
}
}
So in short: I want to subscribe only to specific touch indexes, which also helps me get rid of the if (index != touchIndexToListen) check in other monobehaviours.
The reason I'm doing this touch manager is because I want a clean way to handle mouse input using the same class and I need to be able to fire the ended event when app is minimized in Android. I've left those parts out of this illustration, since they are irrelevant to this question.

First of all one important note: The i used for touches[i] is NOT guaranteed to refer to the same Touch across multiple frames!
For that you rather want to use the Touch.fingerId
The unique index for the touch.
All current touches are reported in the Input.touches array or by using the Input.GetTouch function with the equivalent array index. However, the array index is not guaranteed to be the same from one frame to the next. The fingerId value, however, consistently refers to the same touch across frames. This ID value is very useful when analysing gestures and is more reliable than identifying fingers by their proximity to previous position, etc.
Touch.fingerId is not the same as "first" touch, "second" touch and so on. It is merely a unique id per gesture. You cannot make any assumptions about fingerId and the number of fingers actually on screen, since virtual touches will be introduced to handle the fact that the touch structure is constant for an entire frame (while in reality the number of touches obviously might not be true, e.g. if multiple tappings occur within a single frame).
The array makes no sense actually. event can only be used for a single delegate (Action is just a shorthand for a delegate void Action();) it can't be used for an Action[].
You actually can store a single Action for each index and then use the += and -= operators on it.
You could go a complete different way and use a pattern like
public class TouchHandler : MonoBehaviour
{
private const int MAX_TOUCH_COUNT = 2;
// Store callback Actions by phase and index
// NOTE: I would still pass in the actual Touch in order to be able to use the information in it
private readonly Dictionary<TouchPhase, Dictionary<int, Action<Touch>>> _touchActions = new Dictionary<TouchPhase, Dictionary<int, Action<Touch>>>
{
{TouchPhase.Began, new Dictionary<int, Action<Touch>>()},
{TouchPhase.Ended, new Dictionary<int, Action<Touch>>()}
};
// I would keep one where the listeners can still check "manually"
public event Action<Touch> generalTouchEvent;
public void Subscribe(TouchPhase phase, int touchIndex, Action<Touch> action)
{
if (touchIndex < 0 || touchIndex > MAX_TOUCH_COUNT)
{
Debug.LogError($"Touch index {touchIndex} is not supported!", this);
return;
}
// First get the according inner dictionary by TouchPhase
if (!_touchActions.TryGetValue(phase, out var touchPhaseActions))
{
Debug.LogError($"Touch phase {phase} is not supported!", this);
return;
}
// Next check if there already is an action for given index
if (touchPhaseActions.TryGetValue(touchIndex, out var touchAction))
{
// If it already exists we append the new action to the existing one
// Unsubscribing is fine even if it wasn't added before
// This just makes sure it is only added once
touchAction -= action;
touchAction += action;
}
else
{
// otherwise this new action is the only one for now
touchAction = action;
}
// (over)write it back into the dictionary
touchPhaseActions[touchIndex] = touchAction;
}
public void UnSubscripe(TouchPhase phase, int touchIndex, Action<Touch> action)
{
if (touchIndex < 0 || touchIndex > MAX_TOUCH_COUNT)
{
Debug.LogError($"Touch index {touchIndex} is not supported!", this);
return;
}
// First get the according inner dictionary by TouchPhase
if (!_touchActions.TryGetValue(phase, out var touchPhaseActions))
{
Debug.LogError($"Touch phase {phase} is not supported!", this);
return;
}
if (touchPhaseActions.TryGetValue(touchIndex, out var touchAction))
{
touchAction -= action;
touchPhaseActions[touchIndex] = touchAction;
}
else
{
Debug.LogWarning($"Nothing was listening to {phase} on index {touchIndex} anyway");
}
}
private void Update()
{
if (Input.touchCount > 0)
{
// Get all touches, order them ascending by their fingerId then take up to MAX_TOUCH_COUNT of them
foreach (var t in Input.touches.OrderBy(t => t.fingerId).Take(MAX_TOUCH_COUNT))
{
InvokeTouchEvent(t);
}
}
}
private void InvokeTouchEvent(Touch touch)
{
generalTouchEvent?.Invoke(touch);
if (!_touchActions.TryGetValue(touch.phase, out var touchPhaseActions))
{
return;
}
if (!touchPhaseActions.TryGetValue(touch.fingerId, out var touchAction))
{
return;
}
touchAction?.Invoke(touch);
}
}
and then on the listener do e.g.
public class TouchListener : MonoBehaviour
{
[SerializeField] private TouchHandler _touchHandler;
[SerializeField] public int touchIndexToListenTo;
private void Start()
{
_touchHandler.Subscribe(TouchPhase.Began, touchIndexToListenTo, OnTouchBegan);
_touchHandler.Subscribe(TouchPhase.Ended, touchIndexToListenTo, OnTouchEnded);
_touchHandler.generalTouchEvent += OnGeneralTouchEvent;
}
private void OnGeneralTouchEvent(Touch touch)
{
Debug.Log($"Received a general callback for {touch.phase} with index {touch.fingerId}!", this);
}
private void OnTouchEnded(Touch touch)
{
Debug.Assert(touch.fingerId == touchIndexToListenTo, $"Why do I get an event for {touch.fingerId} if I'm only listening to {touchIndexToListenTo}?!", this);
Debug.Assert(touch.phase == TouchPhase.Ended, $"Why do I get an event for {touch.phase} if I'm only listening to {TouchPhase.Ended}?!", this);
Debug.Log($"Received a {touch.phase} event for index {touch.fingerId}", this);
}
private void OnTouchBegan(Touch touch)
{
Debug.Assert(touch.fingerId == touchIndexToListenTo, $"Why do I get an event for {touch.fingerId} if I'm only listening to {touchIndexToListenTo}?!", this);
Debug.Assert(touch.phase == TouchPhase.Began, $"Why do I get an event for {touch.phase} if I'm only listening to {TouchPhase.Began}?!", this);
Debug.Log($"Received a {touch.phase} event for index {touch.fingerId}", this);
}
}

You can use EventHandlerList for subscribing multiple kind of event in same object.
Be aware that keys are references, so passing int there and retrieving it by value will not work. You must save object references somewhere to be able to fire specific events.
Simple purpose demo app here:
class Program
{
static void Main(string[] args)
{
EventHandlerList _eventList = new EventHandlerList();
var mouseHandler = new MouseHandlerClass();
var appStateHandler = new AppStateHandlerClass();
//attach mouse handlers
_eventList.AddHandler(mouseHandler, (Action<int>)mouseHandler.DoSomething);
_eventList.AddHandler(mouseHandler, (Action<int>)mouseHandler.DoAnotherThing);
//attach appState handlers
_eventList.AddHandler(appStateHandler, (Action<int>)appStateHandler.DoSomething);
//fire mouse event
(_eventList[mouseHandler] as Action<int>).Invoke(99);
//fire appState event
(_eventList[appStateHandler] as Action<int>).Invoke(52);
}
}
public class MouseHandlerClass
{
public void DoSomething(int input)
{
Console.WriteLine($"MouseHandler processed: {input}");
}
public void DoAnotherThing(int input)
{
Console.WriteLine($"MouseHandler processed another thing: {input}");
}
}
public class AppStateHandlerClass
{
public void DoSomething(int input)
{
Console.WriteLine($"AppStateHandlerClass processed: {input}");
}
}
Edit
The handler method signature can be simplified to Action if you don't need to pass any parameters to attached handlers

Related

why this in a callback causes the code to stop?

After recovering my data with Firebase using a callback in GetValueAsync().ContinueWith(task..) , I would like to instantiate my prefab in order to see the list of scores for my leaderboard. But, it does nothing and I have no errors. The code simply stops in the callback UseSores as soon as it come across on a 'this' or a 'instantiate'.
public class Leaderboardmanager : MonoBehaviour
{
public GameObject rowLeardBoard;
FirebaseDB_Read read;
float positionX;
int nbRows = 10;
void Start()
{
read = (gameObject.AddComponent<FirebaseDB_Read>());
GetScorePlayer();
}
void GetScorePlayer()
{
read.GetScores(UseScores, "entries/LeaderBoard/", nbRows);
}
void UseScores(IList<FirebaseDB_Read.Score> scores)
{
Debug.Log("arrive here");
positionX = this.transform.position.y;
Debug.Log("does not arrive here");
}
}
Here is to get my data :
public class FirebaseDB_Read : MonoBehaviour
{
public class Score
{
public string UID;
public string score;
public int rank;
}
public void GetScores(Action<IList<Score>> callback, string URL_TO_SCORES, int limit)
{
DatabaseReference scoresRef = FirebaseDatabase.DefaultInstance.GetReference(URL_TO_SCORES);
scoresRef.OrderByChild("score").LimitToLast(limit).GetValueAsync().ContinueWith(task =>
{
DataSnapshot snapshot = task.Result;
IList<Score> objectsList = new List<Score> { };
int i = 1;
foreach (var childSnapshot in snapshot.Children)
{
Score score = new Score();
score.rank = i;
score.UID = childSnapshot.Child("UID").GetValue(true).ToString();
score.score = childSnapshot.Child("score").GetValue(true).ToString();
objectsList.Add(score);
i++;
}
callback(objectsList);
});
}
}
This is an often asked problem in Unity: Because you ContinueWith on a background thread!
Unity isn't thread-safe, meaning that most of the Unity API can only be used within the Unity main thread.
Firebase offers an extension specifically for Unity: ContinueWithOnMainThread which assures that the result is handled in the Unity main thread where accessing the API is valid.
scoresRef.OrderByChild("score").LimitToLast(limit).GetValueAsync().ContinueWithOnMainThread(task =>
{
...
});
As alternative you can use kind of a so called "main thread dispatcher" pattern and make sure that the callback is executed in the main thread on the receiver side. The advantage of this would be that the still expensive operations on your list are all executed on a background thread, not affecting the UI performance
scoresRef.OrderByChild("score").LimitToLast(limit).GetValueAsync().ContinueWith(task =>
{
...
});
but then on receiver side in FirebaseDB_Read
private readonly ConcurrentQueue<Action> _mainThreadActions = new ConcurrentQueue<Action>();
private void Update()
{
if(_mainThreadAction.Count > 0)
{
while(_mainThreadActions.TryDequeue(out var action))
{
action?.Invoke();
}
}
}
void GetScorePlayer()
{
read.GetScores(UseScores, "entries/LeaderBoard/", nbRows);
}
void UseScores(IList<FirebaseDB_Read.Score> scores)
{
// handle this in the next main thread update
_mainThreadActions.Enqueue(() =>
{
Debug.Log("arrive here");
positionX = this.transform.position.y;
Debug.Log("does not arrive here");
}
}
which on the offside of course introduces a little overhead for checking for any new actions in Update of course. So if you plan do use multiple of such background actions make sure to implement them in one central place in order to keep the overhead limited ;)

Find reference in difference scene unity

I'm confused about finding reference GameObject but different Scene and set the onclick when difference scene, so I have GameManager who manage all but available only on the Main menu. So I decide to make Dontdestroyonload, the issue start at this, so when I play to the MainGame Scene, the field of GameManager at inspector will find, but I can't drag n drop different scene, right? That confuses me.
And if the GameManager at the MainMenu scene, the question is how to drag n drop at the onClick event, like I want pause button active or something else in the game.
]3
I tried with onLloadscene(scene s, Mode mode), but nothing happens, and here the scrip for the GameManager. :
public static GameManager gameManager;
[Header("Main Menu panels")]
public GameObject startPanel;
public GameObject settingPanel;
public GameObject levelPanel;
[Header("InGame Panels")]
#region Panel
public GameObject pausePanel;
public GameObject ObjectivePanel;
public GameObject shopPanel;
private int click = 0;
[Header("Int Tweaks")]
public int indexLevel;
public int onlevel;
public bool isPaused;
_levelSelect LevelSelect;
public static GameManager Instance { set; get; }
public int levelindexPlayerPrefs;
private void Awake()
{
if (gameManager != null)
{
Instance = this;
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
void Start()
{
LevelSelect = FindObjectOfType<_levelSelect>();
OnStart();
onlevel = int.Parse(LevelSelect.levelIndex) + 1;
indexLevel = int.Parse(LevelSelect.levelIndex);
getPlayerData();
}
// Update is called once per frame
void Update()
{
ExitApp();
}
public void OnStart()
{
startPanel.SetActive(true);
settingPanel.SetActive(false);
levelPanel.SetActive(false);
}
#region Buttons
public void startbutton()
{
levelPanel.SetActive(true);
startPanel.SetActive(false);
settingPanel.SetActive(false);
}
public void backButtonMainMenu()
{
levelPanel.SetActive(false);
startPanel.SetActive(true);
settingPanel.SetActive(false);
}
public void settingbutton()
{
levelPanel.SetActive(false);
startPanel.SetActive(false);
settingPanel.SetActive(true);
}
public void PauseButton()
{
Time.timeScale = 0f;
pausePanel.SetActive(true);
ObjectivePanel.SetActive(false);
}
public void Resume()
{
Time.timeScale = 1f;
}
#endregion
public void ExitApp()
{
if (Input.GetKey(KeyCode.Escape))
{
click++;
StartCoroutine(ClickTime());
if (click>1)
{
print("Exit Game");
Application.Quit();
}
}
}
IEnumerator ClickTime()
{
yield return new WaitForSeconds(0.5f);
click = 0;
}
public void getPlayerData()
{
levelindexPlayerPrefs = PlayerPrefs.GetInt("LevelIndex", 0);
}
public void updateLevel(int Index)
{
if (levelindexPlayerPrefs < Index)
{
PlayerPrefs.SetInt("LevelIndex", Index);
levelindexPlayerPrefs = PlayerPrefs.GetInt("LevelIndex");
}
}
#region onloadedScenePickRefferences
private void OnEnable()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
pausePanel = GameObject.FindGameObjectWithTag("PausePanel");
ObjectivePanel = GameObject.FindGameObjectWithTag("ObjectivePanel");
}
#endregion
//public IEnumerator EndChapter()
//{
// updateLevel(indexLevel + 1);
// getPlayerData();
//}
Here is what I would probably do:
Have a static class for storing and sharing all your references. It doesn't have to be in any scene but simply "lives" in the assets:
public static class GlobalReferences
{
// as example just for one reference but you can implement the rest equally yourself
// here this class actually stores the reference
private static GameObject startPanel;
// A public property in order to add some logic
// other classes will always access and set the value through this property
public static GameObject StartPanel
{
get
{
// if the reference exists return it right away
if(startPanel) return startPanel;
// as a fallback try to find it
startPanel = GameObject.FindGameObjectWithTag("StartPanel");
// ofcourse it might still fail when you simply try to access it
// in a moment it doesn't exist yet
return startPanel;
}
set
{
startPanel = value;
// invoke an event to tell all listeners that the startPanel
// was just assigned
OnStartPanelReady?.Invoke();
}
}
// An event you will invoke after assigning a value making sure that
// other scripts only access this value after it has been set
// you can even directly pass the reference in
public static event Action<GameObject> OnStartPanelReady;
}
So now in your component(s) that is(are) in the new loaded scene you assign the value as early as possible (Awake). Here you can already store it via the Inspector since it is a scene reference:
public class ExampleSetter : MonoBehaviour
{
// already reference it via the Inspector
[SerializeField] private GameObject startPanel;
private void Awake()
{
// as a fallback
if(!startPanel) startPanel = GameObject.FindObjectWithTag("startPanel");
// assign it to the global class
GlobalReferences.StartPanel = startPanel;
}
}
And in other scenes that where already loaded before you add a listener so they do their stuff as soon as the other scene is ready:
public class ExampleConsumer : MonoBehaviour
{
[Header("Debug")]
[SerializeField] private GameObject startPanel;
private void Awake()
{
// Try to get the reference
startPanel = GlobalReferences.StartPanel;
// if this failed then wait until it is ready
if(!startPanel)
{
// it is save to remove callbacks even if not added yet
// makes sure a listener is always only added once
GlobalReferences.OnStartPanelReady -= OnStartPanelReady;
GlobalReferences.OnStartPanelReady += OnStartPanelReady;
}
// otherwise already do what you want
else
{
OnStartPanelReady(startPanel);
}
}
private void OnDestroy()
{
// always make sure to clean up callbacks when not needed anymore!
GlobalReferences.OnStartPanelReady -= OnStartPanelReady;
}
private void OnStartPanelReady(GameObject newStartPanel)
{
startPanel = newStartPanel;
// always make sure to clean up callbacks when not needed anymore!
GlobalReferences.OnStartPanelReady -= OnStartPanelReady;
// NOTE: It is possible that at this point it is null anyway if another
// class has set this actively to null ;)
if(startPanel)
{
// Now do something with the startPanel
}
}
}
The other way round when you need a reference in the new loaded Scene form the main scene ... it should already be set since the mainscene was loaded first and has already assigned its according references.
Now you can either go for this static class or simply implement the same logic for each reference that needs to be shared directly in an according component where you reference them via drag&drop .. it makes no difference since anyway you will use static fields and events that are not bound to any instance but the type(s) itself.

How to get public int 'currentSlot' from grandchildren

im beginner and still learning please don't hate.
So my script is located in Canvas, (Canvas -> inv -> invslot) but I need to get currentSlot int from a script in invslot gameobj., how would I do that the right way? I've tried this so far but doesn't seem to work at all.
void UpdateUI () {
for (int i = 0; i < slots.Length; i++)
{
if (i < inventory.items.Count) {
currentSlot = GetComponentsInChildren<InventoryScroll>();
slots[i] = currentSlot;
currentSlot.AddItem(inventory.items[i]);
Debug.Log ("Updating UI");
} else
{
slots[i].ClearSlot();
}
}
}
EDIT!
Here is the top of my InventoryUI, where I want to bring the int currentSlot
public Transform itemsParent;
Inventory inventory;
InventorySlot[] slots;
// Start is called before the first frame update
void Start()
{
inventory = Inventory.instance;
inventory.onItemChangedCallback += UpdateUI;
slots = itemsParent.GetComponentsInChildren<InventorySlot>();
}
But the Inventoryscroll goes this way
List<GameObject> slots = new List<GameObject>();
public int currentSlot=0;
int slotsToScroll=3;
void Start() {
foreach(Transform child in this.transform) {
slots.Add(child.gameObject);
}
}
void Update () {
if (Input.GetKeyDown(KeyCode.Alpha1)) {
currentSlot=0;
UpdateDisplay();
}
if (Input.GetAxis("Mouse ScrollWheel") >0){
if (currentSlot<slotsToScroll) {
currentSlot++;
} else {
currentSlot=0;
}
UpdateDisplay();
}
}
void UpdateDisplay() {
for (int i = 0; i < slots.Count; i++)
{
if (i==currentSlot) {
slots[i].transform.GetChild(0).gameObject.SetActive(true);
} else {
slots[i].transform.GetChild(0).gameObject.SetActive(false);
}
}
}
Inventory script
#region Singleton
public static Inventory instance;
void Awake () {
if (instance != null) {
Debug.LogWarning("More than one instance of inventory found!");
return;
}
instance = this;
}
#endregion
public delegate void OnItemChanged();
public OnItemChanged onItemChangedCallback;
public int space = 6;
public List items = new List();
public bool Add (Item item) {
if (!item.isDefaultItem) {
if(items.Count >= space) {
Debug.Log("Not enough inventory space.");
return false;
}
items.Add(item);
if (onItemChangedCallback != null)
onItemChangedCallback.Invoke();
}
return true;
public void Remove (Item item) {
items.Remove(item);
if (onItemChangedCallback != null)
onItemChangedCallback.Invoke();
Careful, Unity has two methods:
GetComponentsInChildren
Returns all components of Type type in the GameObject or any of its children.
this returns a InventoryScroll []!
and GetComponentInChildren
Returns the component of Type type in the GameObject or any of its children using depth first search.
This returns one single InventoryScroll reference, the first one found!
Note the s!
From your description and how you use it in your code it seems like you wanted to use the latter but have an s too much.
The second mistake: From the variable name it sounds like you rather wanted to get an InventorySlot not an InventoryScroll!
So you should use
currentSlot = GetComponentInChildren<InventorySlot>();
Though it is hard to tell what your actual goal is with this code without seeing the types of slots and currentSlot.
It also appears really strange to me that you already get all slots in Start but here you overwrite
slots[i] = currentSlot;
for each i that is i < inventory.items.Coun. Also you iterate through slots.Length but you pass in inventory.izems[i] .. I don't understand what is supposed to happen here exactly.

Detect changes in the value of other objects referenced in unity?

I'm trying to implement a feature that detects a change in the value of another field object reference.
For example, there is an A object, and the B object contains A.
The A object is notified by OnValidate when the field of the A object has changed.
At this time. Is there any way that "B" can detect the change of "A"?
This feature is only required in the Editor and does not include code in Runtime.
public class A : ScriptableObject
{
[SerializeField]
public string team;
private void OnValidate()
{
Debug.Log($"My team name has been changed to {team}.");
}
}
public class B : ScriptableObject
{
[SerializeField]
public A a;
private void OnValidate()
{
Debug.Log($"A changed.");
}
// How can I detect changes to A and call this functions?
private void OnATeamChanged()
{
Debug.Log($"A's team name has been changed to {a.team}.");
}
private void OnADestroyed()
{
Debug.Log($"A is missing.");
}
}
I would also propose to use events but be careful how and when you register and remove listeners!
public class A : ScriptableObject
{
// You don't need [SerializeField]
// public properties are serialized anyway
public string team;
public event Action onChanged;
public event Action onReset;
public event Action onDestroyed;
private void OnValidate()
{
Debug.Log($"My team name has been changed to {team}.");
if(onChanged == null) return;
onChanged.Invoke();
}
// This is called on reset
// But if you override this you have to set
// The default values yourself!
private void Reset()
{
team = "";
if (onReset == null) return;
onReset.Invoke();
}
// Called when object is destroyed
private void OnDestroyed()
{
if(onDestroyed == null) return;
onDestroyed.Invoke();
}
}
But now in B I would not add the listener on Awake since this adds it after every recompile and multiple times! Instead don't forget to "clean up" all listeners you ever add to avoid getting NullReferenceExceptions:
public class B : ScriptableObject
{
// You don't need [SerializeField] since public properties
// are serialized anyway
public A a;
// Internal for removing listeners later
private A lastA;
private void OnValidate()
{
// Apparently something else was changed
if(a == lastA) return;
Debug.Log("reference a changed");
// Unregister listeners for old A reference
if(lastA)
{
lastA.onChanged -= OnAChanged;
lastA.onReset -= OnAReset;
lastA.onDestroyed -= OnADestroyed;
}
// Register listeners for new A reference
// Note that it is allways possible to remove listeners first
// even if they are not there yet
// that makes sure you listen only once and don't add multiple calls
if(a)
{
a.onChanged -= OnAChanged;
a.onReset -= OnAReset;
a.onDestroyed -= OnADestroyed;
a.onChanged += OnAChanged;
a.onReset += OnAReset;
a.onDestroyed += OnADestroyed;
}
lastA = a;
}
// Make allways sure you also remove all listeners on destroy to not get Null reference exceptions
// Note that it is allways possible to remove listeners even if they are not there yet
private void OnDestroy()
{
if(!a) return;
a.onChanged -= OnAChanged;
a.onReset -= OnAReset;
a.onDestroyed -= OnADestroyed;
}
private void OnAChanged()
{
Debug.Log("A was changed");
}
private void OnAReset()
{
Debug.Log("A was reset");
}
private void OnADestroyed()
{
Debug.Log("a was destroyed");
}
}
Small optional change if you want
If you want additionally to be able to register other listeners in the Inspector the same way you do for Buttons you could simply exchange the
public event Action xy;
with
public UnityEvent xy;
and remove the if(xy == null) checks.
You would than also replace
a.onChanged -= OnAChanged;
a.onChanged += OnAChanged;
by
a.onChanged.RemoveListener(OnAChanged);
a.onChanged.AddListener(OnAChanged);
You could try to add an event
public class A : ScriptableObject
{
[SerializeField]
public string team;
public Action RaiseChangeName;
private void OnValidate()
{
Debug.Log($"My team name has been changed to {team}.");
if(RaiseChangeName != null) { RaiseChangeName(); }
}
}
public class B : ScriptableObject
{
[SerializeField]
public A a;
void Awake()
{
a.RaiseChangeName += OnATeamChanged;
}
// How can I detect changes to A and call this functions?
private void OnATeamChanged()
{
Debug.Log($"A's team name has been changed to {a.team}.");
}
}

What are ways to control the time delay in Unity?

I've looked around and apparently I've got the choice between these libraries/ solutions:
One:
public void Awake() {
Invoke("InvokeAndPrint", 2);
}
void InvokeAndPrint() {
print("InvokeAndPrint 2");
}
Two:
void Start() {
StartCoroutine(WaitAndPrint(2.0F));
}
IEnumerator WaitAndPrint(float waitTime) {
yield return new WaitForSeconds(waitTime);
print("WaitAndPrint " + Time.time);
}
I want to know if there is any other better way?
This is a summary of my comments above
The only other method I can think of is old-school take note of the time at start; then in your Update() method check for elapsed time. You essentially do everything yourself. Though way more verbose than the above examples, it's type-safe and does not require any extra threads or thread job objects.
Simplest
First we need some fields defined:
private DateTime _start;
private bool _done;
In your start take note of the time:
void Start()
{
_start = DateTime.Now;
}
...then in your update check to see how much time has elapsed. If its greater than your timeout of say 2 seconds, fire off what-ever you wish to do - in this case print():
void Update()
{
if (! _done && (DateTime.Now - _start).TotalSeconds >= 2)
{
print("hello world");
_done = true;
}
}
That's it.
Re-usable Code
You'll probably find that there are many places where there is a need for this so wouldn't it be groovy if there was a way to cut down on repeated code. Perhaps a class to wrap it up in?
class DelayedJob
{
private readonly TimeSpan _delay;
private readonly Action _action;
private readonly DateTime _start;
public DelayedJob(TimeSpan delay, Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
_delay = delay;
_action = action;
_start = DateTime.Now;
}
/// <summary>
/// Updates this instance.
/// </summary>
/// <returns>true if there is more work to do, false otherwise</returns>
public bool Update()
{
if (DateTime.Now - _start >= _delay)
{
_action();
return false;
}
return true;
}
}
Then you could do something like this:
void Start()
{
_job = new DelayedJob(TimeSpan.FromSeconds(2), ()=> print("hello"));
}
...after updating your Update() accordingly:
void Update()
{
if (_job != null && !_job.Update())
{
_job = null;
}
}
Multiple Jobs
It's just a matter of placing them in a collection and processing it at runtime.
private List<DelayedJob> _jobs;
void Start()
{
_jobs = new List<DelayedJob>
{
new DelayedJob(TimeSpan.FromSeconds(2), () => print("star wars")),
new DelayedJob(TimeSpan.FromSeconds(3f), () => print("is coming!"))
};
}
...a few alterations to Update():
void Update()
{
bool again;
do
{
again = false;
// you probably want to optimise this so that we don't check the same items
// at the start again after removing an item
foreach (var delayedJob in _jobs)
{
if (!delayedJob.Update())
{
_jobs.Remove(delayedJob);
again = true; // start over
break;
}
}
}
while (again);
}

Categories

Resources