I put a screenshot that will tell you everything.
private Transform[] hiddenObjects;
void Start()
{
leftImageRandom = new Randomizer(0, LeftImageSequence.transform.childCount - 1, true);
DoStart();
}
private void DoStart()
{
leftImageIndex = leftImageRandom.getRandom();
LeftImageSequence.setCurrentChildIndex(leftImageIndex);
RightImageSequence.setCurrentChildIndex(leftImageIndex);
//take hidden objects and put them in an array
hiddenObjects = RightImageSequence.CurrentChild.transform.GetChild(0).transform.GetComponentsInChildren<Transform>();
for(int i=1;i<hiddenObjects.Length;i++)
hiddenObjects[i].gameObject.GetOrAddComponent<MouseEventSystem>().MouseEvent += ClickedHiddenObject;
Debug.Log(hiddenObjects.Length);
}
private void ClickedHiddenObject(GameObject target, MouseEventType type)
{
if (type == MouseEventType.CLICK && CanClick)
{
int targetIndex = System.Array.IndexOf(hiddenObjects, target.gameObject);
Debug.Log(targetIndex);
hiddenObjects[targetIndex].GetComponent<SpriteRenderer>().DOFade(1f, 0.3f).SetEase(Ease.Linear);
}
}
I have a targetIndex that needs to return the index of the object I clicked on. Each object contains the PoligonCollider2D component. The problem is that it always returns -1 to any object. What's the problem, what am I doing wrong?
From your code:
private Transform[] hiddenObjects;
...
System.Array.IndexOf(hiddenObjects, target.gameObject)
hiddenObjects
is an array of Transform
, but target.gameObject
is a GameObject
(actually target
is already a GameObject, so this is redundant): the types don't match, so indeed a GameObject
is never gonna be equal to a Transform
.
Instead try:
System.Array.IndexOf(hiddenObjects, target.transform)