ConditionalWeakTables and you #22
ErroneousCreationist
started this conversation in
Resources
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Storing data on something can be an issue in your rain world mod, as you cannot just directly add variables to something. However, there is a solution... ConditionalWeakTables, or CWTs.
What are they?
A ConditionalWeakTable is a table that, like a dictionary, has a key and value. However, it uses weak references, which means it will not keep memory allocated and prevents leaks and other bad stuff. (This definition is off the top of my head, feel free to think of something better lol)
Getting started
To make a CWT, you need to be using
System.Runtime.CompilerServices
, put that at the top of your cs file. Then, you can create one, like this:public static ConditionalWeakTable<KEY, VALUE> MyCWT= new ConditionalWeakTable<KEY, VALUE>();
The key and value are very important. Lets say you are doing the most common thing, and storing data on your custom slugcat. In that case, you can use Player as your key, and a struct that has your data in it.
How to use
To use your CWT you need to add your player to it when they are created, and use data from the CWT to do stuff you need. You can hook to the players ctor and add to it like this:
Then, you can use TryGetValue to retrieve your struct (put it in an if statement for security, in case it doesn't exist or something, since this returns false if it cant find your key):
Lets say you want to change a value in your CWT. That is a bit harder than a normal dictionary because of some reason (i dunno) but you can do it like this:
Conclusion
I dunno what to write here. Good coding!
Beta Was this translation helpful? Give feedback.
All reactions