How to create a function that can be used on multiple variables when called.

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

so I am trying to learn more with godot, and this may have been asked and I just don’t know how to phrase it properly to find the answers I am looking for any help would be appreciated.


What I am trying to accomplish is to create a function that will run in my UpdateUI() function that will give me a modifier for a stat, that I can run for all of my stats. In my mind something along these lines is what it should look like, but I am unsure if this is right and if it is I am unsure as to why it doesn’t work for me.

var strength = 10
var strMod = 0

func UpdateUI():
       modifierScore(strength, strMod)
       $strLBL.text = str(strength)
       $strModLBL.text = str(strMod)

func modifierScore(ability, modifier):
       modifier = (ability / 2) - 5
       return modifier

I would like to keep it as a function so that I can call this function for each stat that I will be giving to my player, or would it be simpler to just move the code to the variable for each one?

:bust_in_silhouette: Reply From: Merlin1846

The function is not actually doing anything since it simply returns a value and not setting it to anything. You have to set the value in some way for it to do anything. You can do it this way.

var strength = 10
var strMod = 0

func UpdateUI():
   strength = modifierScore(strength, strMod)
   $strLBL.text = str(strength)
   $strModLBL.text = str(strMod)

func modifierScore(ability, modifier):
   modifier = (ability / 2) - 5
   return modifier

Or this way for basics.

var strength = 10
var strMod = 0

func UpdateUI():
   modifierScore(strength, strMod)
   $strLBL.text = str(strength)
   $strModLBL.text = str(strMod)

func modifierScore(ability, modifier):
   modifier = (ability / 2) - 5
   strength = modifier

A super dynamic ( but maybe not the best for performance ) way to do things is this. This takes the name of a variable and sets it.

var strength = 10
var strMod = 0

func UpdateUI():
   modifierScore(strength, strMod)
   $strLBL.text = str(strength)
   $strModLBL.text = str(strMod)

func modifierScore(ability, modifier, variable_name: StringName):
   modifier = (ability / 2) - 5
   set(variable_name, modifier)

Any of those will make the code do something however I noticed that you pass in the argument modifier but then use = to set it to a value meaning that this is equivalent.

func modifierScore(ability):
   return (ability / 2) - 5

You are probably trying to use it as a base in which you want to -+*/ depending on what you need.

func modifierScore(ability, modifier):
   modifier += (ability / 2) - 5
   return modifier