I need help with C# setter

Godot Version

4.3

Question

I created a public int and wanted to assign a custom set function but got error
CS8050 - Only automatically implemented properties or properties that use the “field” keyword can have initializers.
Here is the code:

[Export(PropertyHint.Range, "1, 64, 1")] public int Quantity 
{ 
	get 
	{ 
		return Quantity; 
	} 
	set 
	{
		if (value > 1 && !(item_DATA.stackable))
		{
			Quantity = 1;
			GD.PushError($"{item_DATA.name} is not stackable, setting quantity to 1");

		}
		else
		{
			Quantity = value;
		}
    } 
} = 1;

You have infinite loop here.
Quantity = value will use setter too and start another Quantity = value…
This why you needed add private int quanity and use in your public Quantity setter and getter.
And this will slove your other problem because quality can be set to 1 outside Quantity.

1 Like
private int quantity = 1;
[Export(PropertyHint.Range, "1, 64, 1")] public int Quantity
{
	get
	{
		return quantity;
	}
	set
	{
		if (value > 1 && !(item_DATA.stackable))
		{
			quantity = 1;
			GD.PushError($"{item_DATA.name} is not stackable, setting quantity to 1");
		}
		else
		{
			quantity = value;
		}
	}
}

Something like this ?

Yes :slight_smile: that should work

1 Like