- Home /
Problem with the algorithm when deleting an object
I have a words game. The game has the function of removing an extra letter. I keep the letters in an empty game object.
if (randomCharsString.Length > 0)
{
// We stand in front of the letter that we will delete
int l = randomCharsString.Length - 1;
// find the object of the letter in lettersGrid
GameObject g = lettersGrid.transform.Find(randomCharsString[l].ToString()).gameObject;
// remove a letter from a string
randomCharsString = randomCharsString.Remove(l, 1);
// get the position of a letter in the grid before deleting it
int gOldSabling = g.transform.GetSiblingIndex();
// remove a letter from lettersGrid
Destroy(g);
if (g == null)
{
print("deleted");
}
// for the place of a letter in the spilled empty cell
inputImage = Instantiate(transparentСellPref, lettersGrid);
inputImage.transform.SetSiblingIndex(gOldSabling);
inputImage.gameObject.name = "transparentСell";
// the current state of the letters in lettersGrid
savedLettersGridCharsString = "";
foreach (Transform letter in lettersGrid)
{
if (letter.tag != "transparentСell")
{
savedLettersGridCharsString = savedLettersGridCharsString + letter.tag;
}
}
PlayerPrefsDB.LettersGridCharsString = savedLettersGridCharsString;
PlayerPrefsDB.RandomCharsString = randomCharsString;
print(savedLettersGridCharsString);
App.money -= 1;
PlayerPrefsDB.Money = App.money;
moneyText.text = "" + App.money;
The fact is that the algorithm removes the letter-object and then writes down everything remaining in the string. This is necessary to play the state in case the player left the game and entered later. But the problem is that the number of letters in the line does not match the number of game objects. There is still one extra letter in the line. My brain is already boiling.
Hmm... This isn't a complete answer, so I'm just commenting. In this case, I think it would be much easier to not directly tie each gameObject to a letter. Have you considered abstracting your letter data within a class? I'm not sure I completely understand what you're trying to accomplish, but I think an abstraction of it would look something like this (this isn't tested):
public class LetterTileGrid
{
LetterTile[,] m_LetterTiles;
int m_Rows = -1;
int m_Columns = -1;
public LetterTile[,] letterTiles { get { return m_LetterTiles; } }
public int rows { get { return m_Rows; } }
public int columns { get { return m_Columns; } }
public LetterTileGrid(int rows, int columns)
{
m_LetterTiles = new LetterTile[rows, columns];
m_Rows = rows;
m_Columns = columns;
}
// Get a string represenation of the grid
override public string ToString()
{
string gridRepresentation = "Letter Tile Grid:\n";
for (int i = 0; i < m_Rows; ++i)
{
for (int j = 0; j < m_Columns; ++j)
gridRepresentation += m_LetterTiles[i, j].letter + ", ";
gridRepresentation += "\n";
}
return gridRepresentation;
}
public struct LetterTile
{
public bool isRemoved;
public char letter;
}
}