Advertisement
Guest User

Untitled

a guest
May 24th, 2018
980
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. I can't find a clean and simple way to initialise a public variable in Unity (C#) that doesn't cause me problems.
  2.  
  3. Method 1: declare and initialise at the start of the class:
  4.  
  5. public class Unit {
  6. public int actionIndex = 0;
  7.  
  8. Problem: this variable shows in the Inspector for any object with this component, set to 0, but this will now silently override any change to the actual line of code. So if I change the code to:
  9. public int actionIndex = -1;
  10. The value is still 0 on every object with this component. This breaks my brain, I just lost an hour trying to figure out why this var was always 0 when no line of my code could ever possibly set it to that.
  11.  
  12.  
  13. Method 2: same but use [HideInInspector]:
  14.  
  15. public class Unit {
  16. [HideInInspector]
  17. public int actionIndex = 0;
  18.  
  19. Problem: this doesn't prevent the problem above, the hiding is only visual. The inspector still can and does silently override the code, even more silently now :)
  20.  
  21.  
  22. Method 3: declare at start of class, initialise in Awake or Start:
  23.  
  24. public class Unit {
  25. public int actionIndex;
  26. void Awake() {
  27. actionIndex = 0;
  28.  
  29. Problem: this just seems cumbersome, and it has a knock-on cost in how I init private variables. Either I have to basically initialise EVERY variable in two different places, or I only do this for public vars and now I've got two different rules and conventions for different kinds of variables. Every time I change something from public to private or vice versa I have to change where and how it's initialised too.
  30.  
  31.  
  32. Method 4: all vars are private, have public functions for Set and Get:
  33.  
  34. public class Unit {
  35. private int actionIndex = 0;
  36. public int GetActionIndex() {
  37. return actionIndex;
  38. }
  39. public SetActionIndex(int _index) {
  40. actionIndex = _index;
  41. }
  42.  
  43. Problem: this is even more cumbersome, look at that mess.
  44.  
  45.  
  46. Method 5: all vars are private, but wrap them in a public Property.
  47.  
  48. public class Unit {
  49. private int actionIndex = 0;
  50. public int ActionIndex {
  51. get {
  52. return actionIndex;
  53. }
  54. set {
  55. actionIndex = value;
  56. }
  57. }
  58.  
  59. Problem: this is EVEN MORE lines of code to set up one variable, and I don't love having something that looks like a variable but is secretly running a function.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement