Well, thats a weird title. What i am trying to do is identify the object which position matches the gameObjects position that the script is attached to. Hell, that didn't make it better.

Here's my script:

  public Vector2 tilePosition;
  public float tileYPiece;

  void Update()
          tilePosition = transform.position;
          tileYPiece = tilePosition.y + 0.5f;


  void pieceIdentifier()
          if ((tileYPiece) == GameObject.FindGameObjectWithTag("Piece").GetComponent<PieceScript>().piecePosition.y && tilePosition.x == GameObject.FindGameObjectWithTag("Piece").GetComponent<PieceScript>().piecePosition.x)
              //the GameObject I need to reference does something



So the tile position is a Vector2(x, y), and the piece's position is a Vector2 (x, y) as well, and I need to reference the GameObject that shares position with the tile.

I'm confused as hell, if you hadn't noticed, and would reeally like some help

Thanks in advance

  • \$\begingroup\$ If your gameObject has a collider attached, you can find it with an OverlapSphere/OverlapCircle check \$\endgroup\$ – DMGregory Mar 14 '17 at 22:25

I'd suggest one of these 2 options:

  1. (Quick & dirty) Use FindGameObjectsWithTag("Piece") (note the plural in Objects) to get all the pieces and then iterate (or use a List and Linq) over them to find the one(s) which have that location. Put those into a variable and that's the reference you're looking for.

  2. (I like this one better) you could have a data structure for the tile map, say a 2D array of Tile objects. Then in the Tile class, you have the X and Y positions of that Tile and (this is the important bit) a List of Pieces that are currently on that tile. You would update the list on each tile every time a piece is moved to or from that tile. That way you always know all the pieces that are on each tile at any given time. Oh and each Piece could also have a reference to the tile. Then, all you'd need to do is this.MyTile.PieceList to get all the objects on the same tile as the object attached to the script.

(That came out a bit wordy... post a comment if anything is not clear)

  • \$\begingroup\$ @funkastle, did you get it to work? Did this answer help you? \$\endgroup\$ – Leon Mar 20 '17 at 5:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.