setget does not works

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

Hi I am trying this

var level = 1 setget set_level

func ready():
    level = 2

func set_level(lvl):
    print(level) # it does not print anything

Actually I don’t know how to use it and what is it used for
Thanks!

:bust_in_silhouette: Reply From: estebanmolca

Setget is used to validate a property when it is called from outside the class. It is not called locally because if you are editing the class it is assumed that you are the owner or have full access to it. But when the property is modified from outside (an instance of the class or another referenced script or an export) the set function is called if it is defined for that property. Some examples:

class TestSetGet:
    	var prop = 0 setget set_prop
    	func set_prop(p):
    		prop = p + 1000
    
    func _ready() -> void:
    	var test = TestSetGet.new()
    	test.prop = 5
    	print (test.prop) #print 1005
extends Node2D #This is a class with no name

var number = 0 setget set_number

func set_number(num):
	if num > 5:
		num = 5 
	number = num	
func _ready() -> void:
	number = 15 #access local, not trigger the setter and getter 
	print(number) #print 15
	self.number = 15 #access outside whit self
	print(number) #print 5
	pass

Thanks a lot!
But is there any benefit of it

Probably one can also call the function set_number(15) directly

Help me please | 2021-08-24 10:28

I create a Stats class that defines the attributes of a character.
In that class I create the variable level. Then I instantiate the class in each character in my game and assign a value to it:
var st = Stats.new ()
st.level = 1
Later I want to add the strenght property to each character depending on the level. If I use a set function in the level variable I can assign the value of the strenght in this function for example:
strenght = 2 * level
Now every time my character levels up his strength will be multiplied by two automatically.
If later I want to use another formula to calculate the strenght attribute, I just have to modify the set function of the class. This benefits as the project grows in size. This is called encapsulation in object-oriented programming.

Object-oriented programming - Wikipedia

There are more benefits that you discover as you learn and you want to have everything better organized. But at the end of the day the one who decides the final implementation is yourself.

estebanmolca | 2021-08-24 12:21

I wish that I can upvote your comment.
Now I believe using setget is far more better than calling 6 or more functions. My project is already very large and I need to use this smart way

Thanks a lot man!!

Help me please | 2021-08-24 14:59