Godot Version
4.3
Question
Good night, I would like to know how I can get the numbers from my node name. For example, my node is called “HeartPart2” or “HeartPart15”, how can I get just the number and store it in a variable?
4.3
Good night, I would like to know how I can get the numbers from my node name. For example, my node is called “HeartPart2” or “HeartPart15”, how can I get just the number and store it in a variable?
var num_str: String = "HeartPart2"
var num: int = num_str.right(num_str.length()-9).to_int()
print(num)
You could replace the string line, and all the num_str’s with something like ‘node.name’ to get the the name from your nodes, assuming they all start with ‘HeartPart’ you just need to discard the first 9 characters.
Ryn
You can use RegEx as well for a more flexible solution that will work with any string length.
var string_with_numbers = "HeartPart2 and 7 and HeartPart5"
var regex = RegEx.new()
regex.compile("\\d+")
var all_numbers_found = regex.search_all(string_with_numbers)
for number in all_numbers_found:
var number_found = int(number.get_string())
print(number_found)
# This will print ints 2, 7 and 5
In the case of using “HeartPart15” it will return number_found = 15 as an int.
I loved this solution of removing all the letters and only leaving the numbers at the end. Then just convert it to an integer type! Thank you so much!!
Glad to help…
Ryn
It’s a very interesting solution, it might help me in the future. I still have to study about regular expressions…
Thanks.
I find the best way to handle this is to put the nodes under another node called heartparts. Then you can just get the children and they are in an array. If the numbers are sequential, it’s easy to find your obj with mathematics. HeartPart0, HeartPart1, etc. is heartparts.get_child(0) etc. Arrays are so easy to deal with, generally you want to step through them.
It would be a good idea, but since I’m doing a drag&drop system and these parts can’t be kept within a single node, this solution wouldn’t work for me. Thanks!
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.