Search code examples
c#unity-game-enginemonodevelop

The index value does not increase according to conditions


There are 15 clickable objects on the scene. There are 5 tokens in an array. User needs to match correct 5 with that tokens. User clicks 5 of them (correct five and correct order). So, every time click action called, the code increases the index value. The code uses index to travel along the arrays. But index value keeps turning back to 0. What am I missing here?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class CipherClickHandler : MonoBehaviour, IPointerClickHandler
{
    public Text[] alanlar = new Text[5];
    private string[] clickedWords = new string[5];
    private string[] solution = { "a", "b", "c", "d", "e" };
    private int index = 0;
    private int counter = 0;
    private bool success = false;

    public void OnPointerClick(PointerEventData pointerEventData)
    {
        if (success)
        {
            return;
        }
        else
        {
            if (index < 5)
            {
                clickedWords[index] = this.gameObject.name;
                this.gameObject.SetActive(false);
                alanlar[index].text = clickedWords[index];
                ControlCipher(clickedWords[index]);
                index += 1;
            }
            else
            {
                index = 0;
            }
        }
    }

    private void ClearBlanks()
    {
        ...
    }

    private void ControlCipher(string token)
    {
        if (counter < 5)
        {
            if (token == solution[index])
            {
                counter++;
            }
        }
        else
        {
            PuzzleSolved();
            success = true;
        }
    }

    private void PuzzleSolved()
    {
        ...
    }

    private IEnumerator CoroutineSuccess()
    {
        ...
    }
}

When I trace index just after index < 5 control, it returns 0. When I trace after index += 1, it returns 1. But, after the next click, it again returns 0 and 1 respectively.


Solution

  • The key issue seems to be that each item has a copy of the script, therefore each item has index at . What would fix this would be if they share an index (using static) so that the index can increment and effect for all of them, and be reset should the wrong object be selected.