I have a function that asynchronously loads a xml file, parses it, and adds certain values to a list. I'm using async and await for this. The issue I've run into is that after calling await the program moves on to executing code that accesses that list before the async function has finished adding all items.
My static class with async function:
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Xml.Linq;
using UnityEngine;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.AddressableAssets;
namespace Drok.Localization
{
public static class Localization
{
/// <summary>
/// The currently available languages.
/// </summary>
public static List<string> Available { get; private set; } = new List<string>();
/// <summary>
/// The currently selected language.
/// </summary>
public static string Current { get; private set; } = null;
public static async Task Initialize()
{
await LoadMetaData();
}
private static async Task LoadMetaData()
{
AsyncOperationHandle<TextAsset> handle = Addressables.LoadAssetAsync<TextAsset>("Localization/meta.xml");
TextAsset metaDataFile = await handle.Task;
XDocument metaXMLData = XDocument.Parse(metaDataFile.text);
IEnumerable<XElement> elements = metaXMLData.Element("LangMeta").Elements();
foreach (XElement e in elements)
{
string lang = e.Attribute("lang").Value;
int id = Int32.Parse(e.Attribute("id").Value);
Debug.LogFormat("Language {0} is availible with id {1}.", lang, id);
Available.Add(lang);
}
}
public static void LoadLanguage(string lang)
{
Current = lang;
throw new NotImplementedException();
}
public static string GetString(string key)
{
return key;
}
}
}
The class that initializes it and accesses the list:
using Drok.Localization;
using UnityEngine;
namespace Spellbound.Menu
{
public class LanguageMenu : MonoBehaviour
{
private async void Awake()
{
await Localization.Initialize();
}
private void Start()
{
Debug.Log(Localization.Available.Count);
}
private void Update()
{
}
}
}
I have no idea how to prevent access to that list until after all items have been added. The code I posted just collects info on what languages are available so that only the one language being used can be loaded later.
A Task<T> represents some value (of type T) that will be determined in the future. If you make your property this type, then it will force all callers to await for it to be loaded:
public static class Localization
{
public static Task<List<string>> Available { get; private set; }
static Localization() => Available = LoadMetaDataAsync();
private static async Task<List<string>> LoadMetaDataAsync()
{
var results = new List<string>();
...
results.Add(lang);
return results;
}
}
Usage:
private async Task StartAsync()
{
var languages = await Localization.Available;
Debug.Log(languages.Available.Count);
}
One possibility might be to add some logic to wait for the metadata to be loaded when returning the list from the get accessor.
One way to do this is to have a bool field that is set to true when the list is ready, and then we either return a private backing List<string> or null, depending on the value of our bool field:
public static class Localization
{
private static bool metadataLoaded = false;
private static List<string> available = new List<string>();
// The 'Available' property returns null until the private list is ready
public static List<string> Available => metadataLoaded ? available : null;
private static async Task LoadMetaData()
{
// Add items to private 'available' list here
// When the list is ready, set our field to 'true'
metadataLoaded = true;
}
}
The Awake method is async void, so there is no way for the caller to guarantee that it finishes before moving on to something else.
However, you could preserve the task and await it in the Start method to ensure that it is completed. Awaiting it twice does not harm anything.
public class LanguageMenu : MonoBehaviour
{
private Task _task;
private async void Awake()
{
_task = Localization.Initialize();
await _task;
}
private async void Start()
{
await _task;
Debug.Log(Localization.Available.Count);
}
private void Update()
{
}
}
Expanding on Rufus' comment:
Declare a bool property that's initialized to false. And in your list's getter, return the list only if the said bool property is true, and return maybe null (this depends on your requirements) if false.
public static bool IsAvailable { get; set; } = false;
private static List<string> _available;
public static List<string> Available
{
get
{
if (IsAvailable)
return _available;
else
return null;
}
set { _available = value; }
}
Finally, in your async function, when the work is done set the above property to true.
Latest when there is an Update method involved that should also wait with its execution using async and await might not be enough anyway.
Usually there is always one big alternative to using async for the Unity messages: an event system like e.g.
public static class Localization
{
public static event Action OnLocalizationReady;
public static async void Initialize()
{
await LoadMetaData();
OnLocalizationReady?.Invoke();
}
...
}
And wait for that event in any class using it like e.g.
public class LanguageMenu : MonoBehaviour
{
private bool locaIsReady;
private void Awake()
{
Localization.OnLocalizationReady -= OnLocalizationReady;
Localization.OnLocalizationReady += OnLocalizationReady;
Localization.Initialize();
}
private void OnDestroy ()
{
Localization.OnLocalizationReady -= OnLocalizationReady;
}
// This now replaces whatever you wanted to do in Start originally
private void OnLocalizationReady ()
{
locaIsReady = true;
Debug.Log(Localization.Available.Count);
}
private void Update()
{
// Block execution until locaIsReady
if(!locaIsReady) return;
...
}
}
Or for minimal better performance you could also set enabled = false in Awake and set it to true in OnLocalizationReady then you could get rid of the locaIsReady flag.
No async and await needed.
If you would move the Localization.Initialize(); instead to Start you would give other classes the chance to also add some callbacks before to Localization.OnLocalizationReady in Awake ;)
And you can extend this in multiple ways! You could e.g. together with firering the event directly also pass in the reference to Availables so listeners can directly use it like e.g.
public static class Localization
{
public static event Action<List<string>> OnLocalizationReady;
...
}
and then in LanguageMenu change the signiture of OnLocalizationReady to
public class LanguageMenu : MonoBehaviour
{
...
// This now replaces whatever you wanted to do in Start originally
private void OnLocalizationReady(List<string> available)
{
locaIsReady = true;
Debug.Log(available.Count);
}
}
If anyway LanguageMenu will be the only listener then you could even pass the callback directly as parameter to Initialize like
public static class Localization
{
public static async void Initialize(Action<List<string>> onSuccess)
{
await LoadMetaData();
onSuccess?.Invoke();
}
...
}
and then use it like
private void Awake()
{
Localization.Initialize(OnLocalizationReady);
}
private void OnLocalizationReady(List<string>> available)
{
locaIsReady = true;
Debug.Log(available.Count);
}
or as lambda expression
private void Awake()
{
Localization.Initialize(available =>
{
locaIsReady = true;
Debug.Log(available .Count);
}
}
Update
As to your question about later Initialization: Yes there is a simple fix as well
public static class Localization
{
public static event Action OnLocalizationReady;
public static bool isInitialized;
public static async void Initialize()
{
await LoadMetaData();
isInitialized = true;
OnLocalizationReady?.Invoke();
}
...
}
Then in other classes you can do it conditional either use callbacks or Initialize right away:
private void Awake()
{
if(Localization.isInitialized)
{
OnLocaInitialized();
}
else
{
Localization.OnInitialized -= OnLocaInitialized;
Localization.OnInitialized += OnLocaInitialized;
}
}
private void OnDestroy ()
{
Localization.OnInitialized -= OnLocaInitialized;
}
private void OnLocaInitialized()
{
var available = Localization.Available;
...
}
private void Update()
{
if(!Localization.isInitialized) return;
...
}
Related
For example, there's two classes here.
Class One:
using UnityEngine;
using System.Collections.Generic;
public class One:MonoBehavior
{
private List<string> _assetBundleList;
private void Start()
{
InitializeList();
}
private void InitializeList()
{
//Add assetBundleList field some value.
}
public IEnumerator<string> GetEnumerator()
{
return _assetBundleList.GetEnumerator();
}
}
Class two:
public class Two:MonoBehavior
{
public GameObject gameObjectWithScriptOne;
private One _scriptOne;
private void Start()
{
scriptOne = gameObjectWithScriptOne.GetComponent<One>();
DoSomething();
}
private void DoSomething()
{
foreach(var assetBundle in scriptOne)
{
//Load asset
}
}
}
Script one is just like a manager things, I use this for storing asset bundle data, perhaps the list value will change. Script two must wait for initializing done. Is there any way to wait for it except adjusting script order?
It can be handled with easily creating a context that initialize things sequentially. In short you need to block the main thread.
Let's say you have a root or persistent scene that do must things like loading assets etc.
//The only object in the Root Scene.
public class RootContext : MonoBehaviour
{
private const string _playerAddress = "Player";
public void Awake()
{
//Load assets
//wait for assets loading
//instantiate things.
//new instantiated things can also initalize with this way.
var handle = Addressables.LoadAssetAsync<GameObject>(_playerAddress);
var asset = handle.WaitForCompletion();
var go = Instantiate(bla bla bla);
}
}
I think the what you want is a framework that organize things. You can look at Strange. It is MVCS + IoC framework. Addionality what you said about "when field or property initialization is done" with [PostConstruct] attribute with Strange.
[Inject(ContextKeys.CONTEXT)]
public IContext Context { get; set; }
/*Initialization of injections are guaranteed at here. Their initialization
is also quaranteed like this class.
*/
[PostConstruct]
public void Initalize()
{
}
I'd go with refactoring, but if this is not the case C# events might be the solution.
Class One
public class One:MonoBehavior
{
private List<string> _assetBundleList;
public event Func Initialized;
private void Start()
{
InitializeList();
}
private void InitializeList()
{
//Add assetBundleList field some value.
Initialized?.Invoke();
}
public IEnumerator<string> GetEnumerator()
{
return _assetBundleList.GetEnumerator();
}
}
Class Two:
public class Two:MonoBehavior
{
public GameObject gameObjectWithScriptOne;
private One _scriptOne;
private void Start()
{
scriptOne = gameObjectWithScriptOne.GetComponent<One>();
scriptOne.Initialized += DoSomething;
}
private void DoSomething()
{
foreach(var assetBundle in scriptOne)
{
//Load asset
}
}
}
Also, you should unsubscribe from events when disabling an object, but you'll figure it out by yourself.
I need to wait until a scene is fully loaded in order to move a gameObject to it from DontDestroyOnLoad scene. If I do it too soon (just after calling SceneManager.LoadScene()) then the gameObject disappears. Based on this post I implemented a scene loading class to solve this issue:
public static class CustomSceneManager
{
public delegate void SceneChange(string sceneName);
public static event SceneChange LoadScene;
public static event SceneChange UnloadScene;
private static IEnumerator LoadLevel (string sceneName){
var asyncLoadLevel = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Single);
while (!asyncLoadLevel.isDone){
Debug.Log("Loading the Scene");
yield return null;
}
}
public static void OnLoadScene(string newSceneName)
{
OnUnloadScene(newSceneName);
LoadLevel(newSceneName);
LoadScene?.Invoke(newSceneName);
}
private static void OnUnloadScene(string newSceneName)
{
UnloadScene?.Invoke(newSceneName);
}
}
I'm calling two events from it (LoadScene and UnloadScene). However the LoadLevel(newSceneName) doesn't work - it simply doesn't load a scene. What am I doing wrong here?
EDIT:
Now I'm passing the MonoBehavior reference of the script calling OnLoadScene methid like this:
public static void OnLoadScene(MonoBehaviour loader, string newSceneName)
{
UnloadScene?.Invoke(newSceneName);
loader.StartCoroutine(LoadLevel(newSceneName));
Debug.Log(SceneManager.GetActiveScene().name); // this line returns previous scene
LoadScene?.Invoke(newSceneName);
}
Now the scene loads, but when I check what scene is currently loaded, it returns the previous scene name.
EDIT 2:
To be more precise I replaced Debug.Log(SceneManager.GetActiveScene().name); with Debug.Log(SceneManager.GetSceneByName(newSceneName).isLoaded); and it returns False.
You have to run coroutienes using StartCoroutine.
You either would need to pass in a reference of a MonoBehaviour that will execute the coroutine or simply make your class a Singleton that is never destroyed
Than actually you will invoke your event too early when it is not yet loaded but you just started to load it so rather do e.g.
public class CustomSceneManager : MonoBehaviour
{
public delegate void SceneChange(string sceneName);
public static event SceneChange LoadScene;
public static event SceneChange UnloadScene;
private CustomNetworkManager singleton;
private void Awake ()
{
if(singleton && singleton != this)
{
Destroy(gameObject);
}
singleton = this;
DontDestroyOnLoad (gameObject);
}
private static IEnumerator LoadLevel (string sceneName){
var asyncLoadLevel = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Single);
while (!asyncLoadLevel.isDone){
Debug.Log("Loading the Scene");
yield return null;
}
LoadScene?.Invoke(newSceneName);
}
public static void OnLoadScene(string newSceneName)
{
if(! singleton)
{
singleton = new GameObject("CustomNetworkManager").AddComponent<CustomNetworkManager>();
}
OnUnloadScene(newSceneName);
singleton.StartCoroutine(LoadLevel(newSceneName));
}
Another way you can do this is with an async method.
The catch is that in order to await an AsyncOperation you need a custom awaiter class. There are a few libraries that make it possible, and my favorite one is UniTask.
using Cysharp.Threading.Tasks;
using UnityEngine.SceneManagement;
public static class CustomSceneManager
{
public delegate void SceneChange(string sceneName);
public static event SceneChange LoadScene;
public static event SceneChange UnloadScene;
private static async UniTask LoadLevelAsync(string sceneName)
{
await SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Single);
}
public static async UniTask OnLoadSceneAsync(string newSceneName)
{
OnUnloadScene(newSceneName);
await LoadLevelAsync(newSceneName);
LoadScene?.Invoke(newSceneName);
}
private static void OnUnloadScene(string newSceneName)
{
UnloadScene?.Invoke(newSceneName);
}
}
I have a singleton class and a property that gets set from another class (class b), no problem. I want a different class (class a) to wait indefinitely until the property in the singleton class transitions true. I want the most efficient way possible of doing this, so I felt tasks were ideal, but I can't effectively put all of the pieces together. I don't want to continue to poll and sleep thread.sleep.
public class A
{
public static void Main(string[] args)
{
if(!Monitor.Instance.HasChanged)
{
//await until the task in the Monitor class is complete
}
}
}
public class Monitor
{
private static Monitor instance;
private bool _hasChanged;
private Monitor() { }
public static Monitor Instance
{
get
{
if (instance == null)
{
instance = new Monitor();
}
return instance;
}
}
public bool HasChanged
{
get
{
return _hasChanged;
}
set
{
_hasChanged = value;
if (_hasChanged)
{
//kick off a task
}
}
}
}
public class B
{
private static readonly Monitor _instance;
public void DoSomething()
{
Monitor.Instance.HasChanged = true;
}
}
I would use a TaskCompletionSource for this. You would do something like:
public class Monitor
{
private TaskCompletionSource<bool> _changedTaskSource = new TaskCompletionSource<bool>();
public Task HasChangedTask => _changedTaskSource.Task;
public bool HasChanged
...
set
{
...
_changedTaskSource.TrySetResult(true);
}
}
This sets up a task completion source and completes the task when the value changes. You would wait on it like so:
await Monitor.Instance.HasChangedTask;
One thing that is not clear from your question and you will need to address is resetting the task. To do so, just re-create the TaskCompletionSource.
I would not be surprised if this has been answered somewhere, the problem is I am not sure how to phrase a search to find what I need. The things I have already found have either been too simplistic to be usable or poorly explained such that I cannot translate it into my own project. I had no formal instruction with event handlers, delegates, and the like (heck, I didn't even learn about Entity-Component Systems--or other design patterns--until long after I graduated college and was already employed as a programmer, and even then it wasn't something I learned at, or for, my job).
Essentially what I want to know is, what does the definition of Array.Sort<T>(T[] array, Comparison<T> comparison) look like?
There's clearly some kind of generalization going on, as myCompareDelegate(...) takes two arguments of any type. In almost everything I've found relating to Func arguments, a Func<> parameter requires explicitly declared types, with the exception of some sample code using an operator I am unfamiliar with:
SomeUtility(arg => new MyType());
public void SomeUtility<T>(Func<object, T> converter) {
var myType = converter("foo");
}
It compiles but I have no idea what it does and as such, I do not know how to utilize it to create code that will run or do what I want to do.
My goal here is to be able to create an event system (yes, I'm aware that C# has an event system built in, but again, all the sample code I've seen is either simplified to the point of uselessness--listeners contained in the same class as the dispatcher--or complicated and unexplained). I want the following to be true:
a single function to register an event listener (for any Type of event and its subtypes)
a single function to dispatch an event (calling only the relevant listeners)
to be able to create new event types without having to modify the functions for registration and handling (no explicit types in the dispatcher beyond the base event class) provided the new event type extends the allowable event type (i.e. an Entity will only dispatch EntityEvents not WorldEvents).
I have a system that works currently, but it requires that all my handlers pass through a single "onEvent" function which takes a base event object and figures out what it's actual type is, passing that off to the true handler.
Eg:
//Entity implements IEventDispatcher
public SomeConstructor(Entity ent) {
//public delegate void EventListener(EventBase eventData); is declared
//in the IEventDispatcher interface.
ent.attachEvent(typeof(EntityEventPreRender), new EventListener(onEvent));
ent.attachEvent(typeof(EntityEventPostRender), new EventListener(onEvent));
}
//EntityEventPreRender extends EntityEventRender extends EntityEvent extends EventBase
//EntityEventPostRender extends EntityEventRender extends EntityEvent extends EventBase
public void onEvent(EventBase data) {
if(data is EntityEventPreRender)
onPre((EntityEventPreRender)data);
if(data is EntityEventPostRender)
onPost((EntityEventPostRender)data);
}
public void onPre(EntityEventPreRender evt) {}
public void onPost(EntityEventPostRender evt) {}
attachEvent() here is a function that takes a Type (used as a HashMap key) and a Delegate and stores it in a list (the HashMap value). Dispatching the event just needs to pass the EventData object, which is queried for its type (via evt.GetType()) to retrieve the list of listeners, then invoking them: listItem(evt)
But I'd rather be able to just do this:
public SomeConstructor(Entity ent) {
ent.attachEvent(onPre);
ent.attachEvent(onPost);
}
public void onPre(EntityEventPreRender evt) {}
public void onPost(EntityEventPostRender evt) {}
But I cannot, for the life of me, figure out how to do this because I do not know how to declare the attachEvent() function to take a generic function parameter the way Array.Sort<T>(T[] array, Comparison<T> comparison) does. I get the error:
"The type arguments for method doSomething<T>(SomeClass.Thing<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly."
I think you might be looking for something like the following:
public static class PubSub<TMessage>
{
private static List
<
Action
<
TMessage
>
> listeners = new List<Action<TMessage>>();
public static void Listen(Action<TMessage> listener)
{
if (listener != null) listeners.Add(listener);
}
public static void Unlisten(Action<TMessage> listener)
{
if (listeners.Contains(listener)) listeners.Remove(listener);
}
public static void Broadcast(TMessage message)
{
foreach(var listener in listeners) listener(message);
}
}
In the above code, using PubSub and specifying a type for TMessage creates a new static class in memory with its own memory space allocated for storing a separate list of listeners. The compiler will ensure that only the substituted type for TMessage and its subclasses will be allowed in that list, provided you consistently use the base type as the type argument for the TMessage type parameter.
You would then use it like so:
public class SomeMessageType
{
public int SomeId;
public string SomeDescription;
}
public class SomePublisher
{
public void DoSomethingCool(string description)
{
var randomizer = new Random();
...
PubSub<SomeMessageType>.Broadcast(new SomeMessageType(){SomeId = randomizer.Next(), SomeDescription = description});
}
}
public class SomeListener
{
static SomeListener()
{
PubSub<SomeMessageType>.Listen(SomeMessageEvent);
}
private static void SomeMessageEvent(SomeMessageType message)
{
// do something with the message
}
}
If you then create another class SomeOtherMessageType which does not inherit from SomeMessageType and make similar calls to it, it will only broadcast to listeners of that specific type.
EDITED:
Here is a full proof of concept that compiles that you can run in a console app to allay any remaining concerns you may have over efficacy of this technique.
using System;
using System.Collections.Generic;
namespace TestPubSub
{
public class Program
{
public static void Main(string[] args)
{
Program.startListeners();
Program.sendTestMessages();
Program.stopConsoleFromExitingImmediately();
}
private static void startListeners()
{
SomeListener.Listen();
SomeOtherListener1.Listen();
SomeOtherListener2.Listen();
}
private static void sendTestMessages()
{
var publisher1 = new SomePublisher();
var publisher2 = new SomeOtherPublisher();
publisher1.DoSomethingCool("Hello world");
publisher2.DoSomethingElse(DateTime.Now);
}
private static void stopConsoleFromExitingImmediately()
{
Console.ReadKey();
}
}
public static class PubSub<TMessage>
{
private static List
<
Action
<
TMessage
>
> listeners = new List<Action<TMessage>>();
public static void Listen(Action<TMessage> listener)
{
if (listener != null) listeners.Add(listener);
}
public static void Unlisten(Action<TMessage> listener)
{
if (listeners.Contains(listener)) listeners.Remove(listener);
}
public static void Broadcast(TMessage message)
{
foreach(var listener in listeners) listener(message);
}
}
public class SomeMessageType
{
public int SomeId;
public string SomeDescription;
}
public class SomeOtherMessageType
{
public DateTime SomeDate;
public Double SomeAmount;
}
public class SomePublisher
{
public void DoSomethingCool(string description)
{
var randomizer = new Random();
PubSub<SomeMessageType>.Broadcast(new SomeMessageType(){SomeId = randomizer.Next(), SomeDescription = description});
}
}
public class SomeOtherPublisher
{
public void DoSomethingElse(DateTime when)
{
var randomizer = new Random();
PubSub<SomeOtherMessageType>.Broadcast(new SomeOtherMessageType(){SomeAmount = randomizer.NextDouble(), SomeDate = when});
}
}
public class SomeListener
{
public static void Listen()
{
PubSub<SomeMessageType>.Listen(SomeMessageEvent);
}
private static void SomeMessageEvent(SomeMessageType message)
{
Console.WriteLine("Attention! SomeMessageType receieved by SomeListener with\r\nid: {0}\r\ndescription: {1}\r\n", message.SomeId, message.SomeDescription);
}
}
public class SomeOtherListener1
{
public static void Listen()
{
PubSub<SomeOtherMessageType>.Listen(SomeMessageEvent);
}
private static void SomeMessageEvent(SomeOtherMessageType message)
{
Console.WriteLine("Heads up! SomeOtherMessageType receieved by SomeOtherListener1 with\r\namount: {0}\r\ndate: {1}\r\n", message.SomeAmount, message.SomeDate);
}
}
public class SomeOtherListener2
{
public static void Listen()
{
PubSub<SomeOtherMessageType>.Listen(SomeMessageEvent);
}
private static void SomeMessageEvent(SomeOtherMessageType message)
{
Console.WriteLine("Yo! SomeOtherMessageType receieved by SomeOtherListener2 withr\namount: {0}\r\ndate: {1}\r\n", message.SomeAmount, message.SomeDate);
}
}
}
EDITED AGAIN (Alternate proof of concept using an instance based pubs):
Here is a proof of concept using an instance based PubSub.
using System;
using System.Collections.Generic;
namespace TestPubSub
{
public class Program
{
private static PubSub<SomeMessageType> pubSub1 = new PubSub<SomeMessageType>();
private static PubSub<SomeOtherMessageType> pubSub2 = new PubSub<SomeOtherMessageType>();
private static SomeListener listener1 = new SomeListener();
private static SomeOtherListener1 listener2 = new SomeOtherListener1();
private static SomeOtherListener2 listener3 = new SomeOtherListener2();
public static void Main(string[] args)
{
Program.startListeners();
Program.sendTestMessages();
Program.stopConsoleFromExitingImmediately();
}
private static void startListeners()
{
Program.listener1.Listen(Program.pubSub1);
Program.listener2.Listen(Program.pubSub2);
Program.listener3.Listen(Program.pubSub2);
}
private static void sendTestMessages()
{
var publisher1 = new SomePublisher(Program.pubSub1);
var publisher2 = new SomeOtherPublisher(Program.pubSub2);
publisher1.DoSomethingCool("Hello world");
publisher2.DoSomethingElse(DateTime.Now);
}
private static void stopConsoleFromExitingImmediately()
{
Console.ReadKey();
}
}
public class PubSub<TMessage>
{
private List
<
Action
<
TMessage
>
> listeners = new List<Action<TMessage>>();
public void Listen(Action<TMessage> listener)
{
if (listener != null) this.listeners.Add(listener);
}
public void Unlisten(Action<TMessage> listener)
{
if (listeners.Contains(listener)) this.listeners.Remove(listener);
}
public void Broadcast(TMessage message)
{
foreach(var listener in this.listeners) listener(message);
}
}
public class SomeMessageType
{
public int SomeId;
public string SomeDescription;
}
public class SomeOtherMessageType
{
public DateTime SomeDate;
public Double SomeAmount;
}
public class SomePublisher
{
private PubSub<SomeMessageType> pubSub;
public SomePublisher(PubSub<SomeMessageType> pubSub) { this.pubSub = pubSub; }
public void DoSomethingCool(string description)
{
var randomizer = new Random();
this.pubSub.Broadcast(new SomeMessageType(){SomeId = randomizer.Next(), SomeDescription = description});
}
}
public class SomeOtherPublisher
{
private PubSub<SomeOtherMessageType> pubSub;
public SomeOtherPublisher(PubSub<SomeOtherMessageType> pubSub) { this.pubSub = pubSub; }
public void DoSomethingElse(DateTime when)
{
var randomizer = new Random();
this.pubSub.Broadcast(new SomeOtherMessageType(){SomeAmount = randomizer.NextDouble(), SomeDate = when});
}
}
public class SomeListener
{
public void Listen(PubSub<SomeMessageType> pubSub)
{
pubSub.Listen(this.SomeMessageEvent);
}
private void SomeMessageEvent(SomeMessageType message)
{
Console.WriteLine("Attention! SomeMessageType receieved by SomeListener with\r\nid: {0}\r\ndescription: {1}\r\n", message.SomeId, message.SomeDescription);
}
}
public class SomeOtherListener1
{
public void Listen(PubSub<SomeOtherMessageType> pubSub)
{
pubSub.Listen(this.SomeMessageEvent);
}
private void SomeMessageEvent(SomeOtherMessageType message)
{
Console.WriteLine("Heads up! SomeOtherMessageType receieved by SomeOtherListener1 with\r\namount: {0}\r\ndate: {1}\r\n", message.SomeAmount, message.SomeDate);
}
}
public class SomeOtherListener2
{
public void Listen(PubSub<SomeOtherMessageType> pubSub)
{
pubSub.Listen(this.SomeMessageEvent);
}
private void SomeMessageEvent(SomeOtherMessageType message)
{
Console.WriteLine("Yo! SomeOtherMessageType receieved by SomeOtherListener2 withr\namount: {0}\r\ndate: {1}\r\n", message.SomeAmount, message.SomeDate);
}
}
}
I'm making a game where workers perform actions based on a current Task. Each worker will be assigned a list of tasks, in a preferred order (which is influenced by the player's decisions).
When a task is completed (e.g. take item from X to Y), the worker needs to start a new task by checking through their list of possible tasks, see if each can be performed, and if so, set their current task to that task and start it (the last task - "Wander Around" is always going to be available).
I currently have this working using a big switch statement and Enums, but now want to generalise this code to create a Task class, and give the workers a list of preferred Tasks, a GetNextTask() function, and in the worker's Update() method, call currentTask.update() (this will get the worker to do whatever he's required to do under the current task, and which will call worker.GetNextTask() when the task is complete).
What I'm unclear on is the best way to store Tasks in the worker.
Should I use:
1) Reflection. Store the possible Tasks as a list of types, then use reflection to a) call a static method public static virtual bool CanPerformThisTask() which is overridden in each subclass, and b) Create an instance of that task for the worker?
(example attempt at code for this below - but unable to test yet)
2) Instantiate all the Tasks whenever a worker needs to get a new task (probably using Activator), and check (Task)task.CanPerformThisTask() for each one - if true, do that task. Instantiating them all seems inefficient though?
3) Generics. Can this be done using generics? If so, how?
Here is a snippet of my classes to give the idea of what I'm trying to do:
Worker Class:
protected List<Point> waypoints = new List<Point>();
public bool reachedDestination { get { return waypoints.Count == 0; } }
protected Task task;
public List<Type> possibleTasks;
public Worker(Task initialTask, List<Type> initialPossibleTasks ...)
: base(...)
{
task = initialTask;
possibleTasks = initialPossibleTasks;
}
public override void Update()
{
base.Update();
if (!reachedDestination) Move();
task.Update();
}
public void GetNextTask()
{
foreach (Type t in possibleTasks)
{
//reflection code here - will this work and can we do this with generics instead?
Bool canDoT = (bool)t.GetMethod("CanPerformThisTask", BindingFlags.Static | BindingFlags.Public).Invoke(null, null);
if (canDoT)
{
task = Activator.CreateInstance(t);
return;
}
}
}
Here is some incomplete code for my base Task class (which shouldn't be instantiated):
public class Task
{
public Worker worker;
public virtual static bool CanPerformThisTask()
{
//never call this from here - always from subclasses
return false;
}
public Task()
{
//set up code here
}
public virtual void Update()
{
//make worker do relevant activities here
//call finish task when done
}
public void FinishTask()
{
worker.GetNextTask();
}
}
and here is an example of a Task the worker will have in its list of possible tasks:
public class T_WorkerWander : Task
{
public static override bool CanPerformThisTask()
{
//can always wander (other Tasks will have conditions here)
return true;
}
public T_WorkerWander()
: base()
{
}
override public void Update()
{
//make the worker wander here
if (worker.reachedDestination) FinishTask();
}
}
Update: here is the code I've now got working
Task Class:
public abstract class Task
{
//the entity holding this task
public TaskableEntity taskEntity;
public List<TaskStage> taskStages;
public TaskStage currentTaskStage { get { return taskStages[0]; } }
public Task(TaskableEntity t) { taskEntity = t; }
/// <summary>
/// the conditions for the Task to be started
/// </summary>
public virtual bool CanStart()
{
return true;
}
public void Start()
{
taskStages = new List<TaskStage>();
InitialiseTaskStages();
taskStages[0].Start();
}
public abstract void InitialiseTaskStages();
public void Update()
{
currentTaskStage.Update();
if (currentTaskStage.IsComplete()) TaskStageComplete();
}
public void TaskStageComplete()
{
taskStages.RemoveAt(0);
if (taskStages.Count == 0) taskEntity.TaskComplete();
else currentTaskStage.Start();
}
public void SetTaskStages(params TaskStage[] t)
{
taskStages = t.ToList();
}
public void Interrupt()
{
currentTaskStage.Interrupt();
}
}
TaskStage class:
public sealed class TaskStage
{
private Task task;
private List<Point> pointsToMoveTo;
public void SetPointsToMoveTo(Point p) { pointsToMoveTo = new List<Point>() { p }; }
public void SetPointsToMoveTo(params Point[] p) { pointsToMoveTo = p.ToList(); }
public void SetPointsToMoveTo(List<Point> p) { pointsToMoveTo = p; }
public Action actionToApply;
private float timeToWait;
public void SetWait(float wait) { timeToWait = wait; }
private IReservable[] itemsToReserve;
public void SetItemsToReserve(params IReservable[] items) { itemsToReserve = items; }
private IReservable[] itemsToUnreserve;
public void SetItemsToUnreserve(params IReservable[] items) { itemsToUnreserve = items; }
private Emotion emotionToSet;
public void SetEmotionToSet(Emotion e) { emotionToSet = e; }
private TaskStage _interrupt;
public void SetInterruptAction(TaskStage t) { _interrupt = t; }
public void Interrupt() { _interrupt.Start(); }
public TaskStage(Task t)
{
task = t;
}
public void Start()
{
if (actionToApply != null) actionToApply();
if (itemsToUnreserve != null) UnreserveItems();
if (itemsToReserve != null) ReserveItems();
if (pointsToMoveTo != null)
{
//this will need changing after pathfinding sorted out...
if (pointsToMoveTo.Count == 1) task.taskEntity.SetWaypoints(pointsToMoveTo[0]);
else task.taskEntity.waypoints = pointsToMoveTo;
}
if (emotionToSet != null) emotionToSet.StartEmotion();
}
public void Update()
{
if (timeToWait > 0) timeToWait -= GV.elapsedTime;
}
public bool IsComplete()
{
if (pointsToMoveTo != null && !task.taskEntity.reachedDestination) return false;
if (timeToWait > 0) return false;
return true;
}
public void ReserveItems()
{
foreach (IReservable i in itemsToReserve)
{
i.reserved = true;
}
}
public void UnreserveItems()
{
foreach (IReservable i in itemsToUnreserve)
{
i.reserved = false;
}
}
}
Example Task:
public class T_WorkerGoToBed : Task
{
public FactoryWorker worker { get { return taskEntity as FactoryWorker; } }
public T_WorkerGoToBed(TaskableEntity t)
: base(t) { }
public override bool CanStart()
{
return Room.Available<Bed>(GV.Bedrooms);
}
public override void InitialiseTaskStages()
{
Bed bedToSleepIn = Room.NearestAvailableFurniture<Bed>(GV.Bedrooms, taskEntity.X, taskEntity.Y);
//stage 1 - reserve bed and move there
TaskStage ts1 = new TaskStage(this);
ts1.SetItemsToReserve(bedToSleepIn);
ts1.SetPointsToMoveTo(bedToSleepIn.XY);
//stage 2 - sleep in bed
TaskStage ts2 = new TaskStage(this);
ts2.SetWait((worker.maxEnergy - worker.energy) / worker.energyRegeneratedPerSecondWhenSleeping);
ts2.SetEmotionToSet(new E_Sleeping(worker, false));
//stage 3 - unreserve bed
TaskStage ts3 = new TaskStage(this);
ts3.SetItemsToUnreserve(bedToSleepIn);
ts3.SetEmotionToSet(new E_Happy(worker, false));
SetTaskStages(ts1, ts2, ts3);
}
}
It sounds like you need to reverse responsibility between task and worker. Instead of asking whether the task can be performed, ask the worker if he can perform a given task:
class Worker
{
bool CanPerformTask<T>() where T : Task
{
var type = typeof(T);
// code to determine whether worker can perform the task T
}
// alternative with instance parameter
bool CanPerformTask<T>( T task ) where T : Task
{
// code to determine whether worker can perform the task passed in
}
}
This solution avoids the "instantiate all tasks or call static method" problem.
Also, consider using the built-in collection classes. Things such as queues and stacks can greatly simplify the code needed to schedule execution of things.
I think you are abusing the point of static classes. The "Task" class should be standard (not static). Your "Worker" class is not static therefore implying that there is more than one "Worker" instance. Given this paradigm, these workers can probably have the same task assigned to them.
Your "Worker" class needs to have this property modified from:
public List possibleTasks;
to
public List _possibleTasks;
You probably should not have public access to this property either. You can modify "CanPerformThisTask" as necessary.