- Home /
How to write a custom attribute?
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!
Answer by Loui_Studios · Jan 28, 2017 at 05:08 PM
Since no one was able to help me with my problem, I found a similar question here.
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[i], typeof(TimeVar)) as TimeVar;
if (attribute != null)
Debug.Log(objectFields[i].Name); // The name of the flagged variable.
}
}
}
}
When I run my scene, the names of the marked variables can be seen in the console:
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.
Does this work analogously for Properties ins$$anonymous$$d of Fields, in the event a value is bound to a ui element?
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Finding a method by custom attribute and passing to a UI button 1 Answer
How to get transform syncing over network to work? 1 Answer
Photon position syncing 0 Answers