Getters and setters with C# / run method on exported parameter changed

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Stuntkoala

I have an exported Color and I want a method to be called everytime I change it in the Editor. As I understand in GDScript, this is possible with setget. I tried the following

[Export]
private Color col {
      get {return col;}
      set {col = value; setColor(0, col);}
 }

where setColor is the method I want to call (to change a child nodes material albedo). But this crashed the editor and i can’t even open the project unless I delete .mono.

I know I can also define the class as a Tool and put setColor in the process method, but I would rather not call it every frame unnecessarily.

:bust_in_silhouette: Reply From: Stuntkoala

Ok I asked on Discord and my Idol, my shining star @Dael Grybel got me the answer:

In C#, you didn’t specify an access modifier, so it’s a private property. Properties, with a { get; set; } have an implied private field created behind the scenes. When you decide to customize the property a bit, and make the getter and setter have more logic to it, it no longer creates an implied private field (as I understand), so it’s gonna not know what to do. if you write it like this:

[Tool]
public class myClass : Spatial {
    
     Color col;
    
     [Export]
     Color _col {
         get {return col;}
         set {col = value; 
         setColor(col);}
     }
  }

It should be good.

	[Export] private Texture _texture
{
	get {return _texture;}
	set {_texture = value;
	TileSet.TileSetTexture(0, _texture);
	}
}

straightforward example

boruok | 2020-09-03 13:06