[Solved] C# Tile array trouble

Natey214Natey214 Posts: 8Member
edited October 31 in 2D

I am creating an RTS and am trying to write a method to check the position of each tile within an array, and whether it is occupied. hasBuilding is a public boolean declared in the tile's script. I get errors at the array value in the if and return statements that Tile cannot be converted to an int. I feel like I need a new approach but I'm stumped.

    using Godot;
    using System;

    public class Map : Node
    {
        Tile[] allTiles;
        Tile[] tilesWithBuildings;
        float tileSize = 32.0f;


        public override void _Ready()
        {

        }

        Tile get_tile_at_position (int position)
        {

            foreach(Tile x in allTiles)
            {
                if (allTiles[x].Position == position && allTiles[x].hasBuilding == false)
                return allTiles[x];
            }
            return null;
            }

Tags :

Comments

  • xyzxyz Posts: 527Member

    Inside foreach loop x is a reference to an actual Tile object, it's not an index.

  • Natey214Natey214 Posts: 8Member

    @xyz said:
    Inside foreach loop x is a reference to an actual Tile object, it's not an index.

    Correct, for each tile object I am checking and returning the Tile.Position and whether the hasBuilding boolean is false.

  • xyzxyz Posts: 527Member
    edited October 21

    Yes, but in the loop body you're treating it as it was an index, which is expected to be of integer type not of Tile type, hence the error. x should be directly used as a Tile object. When you iterate through a collection in this manner your iterator variable represents the object itself, not its index. Note that you even declared it as such in the foreach statement (Tile x)

    foreach(Tile x in allTiles){
        if (x.Position == position && x.hasBuilding == false){
             return x;
        }
    }
    

    Of course, some name other than x would be more suitable here.

  • Natey214Natey214 Posts: 8Member

    Ah, thank you! This also revealed that I declared the wrong parameter in the method as well, should have been a Vecor2.

Leave a Comment

BoldItalicStrikethroughOrdered listUnordered list
Emoji
Image
Align leftAlign centerAlign rightToggle HTML viewToggle full pageToggle lights
Drop image/file