when each if statement has 1 city it works, but when I add more than one then it doesn't work.
Systematist Comparison operators have precedence over logical operators and a non-empty string always evaluates to true.
Found how to fix it but I don't know if it's the best fix
`func process(delta):
var city = Globals.CityType
if city == 'New York' or city == 'Beijing' or city == 'Riga':
$TextureRect.texture = load("res://Images/office.png")
elif city == 'Chicago' or city == 'Shanghai' or city == 'Jelgava':
$TextureRect.texture = load("res://Images/sunny.png")
elif city == 'San Diego' or city == 'Chongqing' or city == 'Daugavpils':
$TextureRect.texture = load("res://Images/realistic sunny.png")
`
Systematist Great, but this is not really scalable. Should you decide to add more cities and more images in the future your code might become spaghettified. Better to put all this into an appropriate data structure that maps cities to corresponding images. This way you can avoid excessive if-ing altogether and make your code more readable and easier to manage.
Alys At the very least you should learn match
instead of if elif
when comparing many things to one variable.
match city:
"New York", "Beijing", "Riga":
$TextureRect.texture = load("res://Images/office.png")
"Chicago", "Shanghai", "Jelgava":
$TextureRect.texture = load("res://Images/sunny.png")
"San Diego", "Chongqing", "Daugavpils":
$TextureRect.texture = load("res://Images/realistic sunny.png")
an appropriate data structure that maps cities to corresponding images
Example:
var city_image: Dictionary = {
"New York": "office.png",
"Beijing": "office.png",
"Riga": "office.png",
...
}
if city_image.has(city):
$TextureRect.texture = load("res://Images/" + city_image[city])
else:
print_debug("no image for city '%s'" % city)
© 2022 - 2024 — McMap. All rights reserved.