Accessing items in Array

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

I am trying to access individual cellids in a tilemap. Here is the problem I am facing:

extends TileMap

var cellids = []
var grid_offset = Vector2(16,16)
var spark
var tile_position = {}
var actual_position = []
var temp_position = []
var countingCells
var kount =0
var completed = []

When I run the following code, I get the error given below the code:

func _ready():
	cellids = get_used_cells_by_id(0)
	var i = 0
	tile_position[i] = map_to_world(cellids[i])

Invalid get index ‘0’ (on base: ‘Array’).

However, when I run the following code in a for loop, I get a valid output. I get the output below the code:

func _ready():
	cellids = get_used_cells_by_id(0)
	countingCells = cellids.size()
	for i in range (countingCells):
		tile_position[i] = map_to_world(cellids[i])

(672, 160)
(736, 160)
(864, 176)
(1296, 336)
(96, 448)
(1040, 512)
(736, 560)
(1184, 720)

I know that tile_position is declared as a dictionary. But why am I able to access the values in a for loop and not individually?

Can anyone please explain? How can I correctly access individual values of map_to_world ?

Please help.

Was the error given for tile_position[o] or cellids[0] ?

avnih | 2021-03-24 05:03

Probably the latter since the former is a dictionary

exuin | 2021-03-24 06:56

:bust_in_silhouette: Reply From: Inces

The only reason I can see is that get-used-cells-by-id(0) was empty at the time of running first version of code. Meaning Your tilemap didn’t have any tiles with index 0. Latter version of the code, with for loop, will never throw this error even if array is empty.