Class Getters/Setters

Is it possible to set getters & setters for every instance of a class?
Something like

public myClass{
int myInt = 0;
//Constructor
public myclass(){
get{
return this.myInt+1;
}
set{
this = value;
this.myInt += 1;
}

}
}

void Start(){
myClass test = new myClass();

Debug.Log(test.myInt);
}

Where the debugger should return 2
I tried googling it and couldn’t find any instances, I would drop this into my compiler to test it, but I’m currently away from my computer for some time.
Any help would be much appreciated! Thank you in advance

I think we’ll all just wait for you to get back to your computer and drop it into your compiler yourself to test it. That’s not what this forum is for.

ALSO, if you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: https://discussions.unity.com/t/481379

ALSO, how to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

Use code tags:
https://www.youtube.com/watch?v=84kaypWK1bM

Probably not an ideal solution, but I guess one way to do this is to have a wrapper object that contains a collection of the objects you want to update, then when updating, loops through & passes them all through a callback function.

Something like:

public class SomeClass {
  public string name;
  public int numberOfThings;
  public bool isWhatever;
}

public class MultiSetter<T> {
  private readonly List<T> _items = new List<T>();

  public void Add(T item) => _items.Add(item);

  public void SetAll(Action<T> handler) {
    for(int i = 0; i < _items.Count; i++) {
      handler.Invoke(_items[i]);
    }
  }
}

public class AnotherClass {
  void Example() {
    MultiSetter<SomeClass> setter = new MultiSetter<SomeClass>();

    setter.Add(new SomeClass());
    setter.Add(new SomeClass());
    setter.Add(new SomeClass());

    setter.SetAll((SomeClass someClass) => {
      someClass.name = "Sam";
      someClass.numberOfThings = 32;
    });
  }
}

Edit:
I’m now realizing this is essentially just JavaScript’s Array.forEach function.

1 Like

Seams a bit messy, but smart idea! I may go with a createInstance(){ function in the class
Thanks a bunch for your help :slight_smile: