I am building a 2D turn-based RPG battle scene with Unity 5. The enemies are represented as 2D sprites with box colliders. In my script, the relevant enemy class is defined as:

public class EnemyView : MonoBehaviour {

    public SpriteRenderer _renderer;
    public BoxCollider2D _collider;

    void Awake() {
        _renderer = gameObject.GetComponent<SpriteRenderer>();
        _collider = gameObject.GetComponent<BoxCollider2D> ();

And I have the following code grouping the enemy sprites together:

public class MainGUIView : MonoBehaviour {
    public EnemyView[] _enemyViews;

When a player clicks on an enemy, I would like to know the index of that enemy within the _enemyViews array. I thought of implementing this within EnemyView class but that class has no information about its index, so I am thinking of implementing OnMouseDown() within MainGUIView where I could iterate through _enemyViews to find the one whose collider contains the mouse click point, but I don't know how to write the code. Anyone can point me to some useful code snippet?


1 Answer 1


You can use Dictionary to hold the index data.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

Dictionary<int, EnemyView> _enemyViews;
// populate dictionary

// element access while looping
_enemyViews[i].first;   // gets the index
_enemyViews[i].second;  // gets the EnemyView object
  • 2
    \$\begingroup\$ Thanks. I did it in another way by adding a field public int _index; to EnemyView \$\endgroup\$
    – shapeare
    Nov 30, 2015 at 11:28
  • \$\begingroup\$ Or that. It's even the simpler way. \$\endgroup\$
    – Varaquilex
    Nov 30, 2015 at 12:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .