I have been developing a package in C# to let people reverse time in their games. At the moment it all works fine, but if you want a variable (say health) to be synchronized, you have to code the synchronization for that one variable into the script yourself.
It’s a hassle, and makes it difficult to quickly sync variables.
I am aware that when networking, using the [syncVar]
attribute will tell the server to keep the value of that variable syncronised across all clients.
So how I would write my own custom attribute so that I can flag a variable for synchronization with my custom time reversing code?
Thanks for the help!
Since no one was able to help me with my problem, I found a similar question [here][1].
I’ll leave my solution here, should anyone have the same problem I did.
Following the example from the correct answer, I then wrote an empty attribute and assigned this attribute to the variables I want to be synced up when I am coding the game.
Attribute (for variables only):
[AttributeUsage(AttributeTargets.Field)]
public class TimeVar : Attribute {}
Assigning the attribute to a variable:
[TimeVar] public float shield, armour, health;
Then, from another class, I load in all marked variables:
public class TimeVarSync : MonoBehaviour {
private void Start() {
MonoBehaviour[] sceneActive = FindObjectsOfType<MonoBehaviour>();
foreach (MonoBehaviour mono in sceneActive) {
FieldInfo[] objectFields = mono.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public);
for (int i = 0; i < objectFields.Length; i++) {
TimeVar attribute = Attribute.GetCustomAttribute(objectFields*, typeof(TimeVar)) as TimeVar;*
_ Debug.Log(objectFields*.Name); // The name of the flagged variable._
_ }_
_ }_
_ }_
_}_
When I run my scene, the names of the marked variables can be seen in the console:
_[86883-capture.png*|86883]*
Now that I can I access marked variables, I can write some code to log them at runtime and make scripting the time reversal much, much easier.
_[1]: http://answers.unity3d.com/questions/896763/custom-attributes.html*_
_