I'm developing a TicTacToe game and faced with a some problem.
After put the "X" I need to change changeMove
to true
in ChangeMove()
function. After that get into the ChangeMove()
function again and change place.sprite
to O.sprite
in else if
block.But it isn't changing
Here is my inspector of MainCamera
:
I created a script(PutMove.cs) that inherits all the methods and fields from LogicOfGame.cs besides private bool changeMove
only for clickable squares to put move there:
Here is my LogicOfGame.cs, PutMove.cs scripts and inspector of first square:
The square's inspector:
LogicOfGame.cs:
public class LogicOfGame : MonoBehaviour
{
public SpriteRenderer place;
private bool changeMove;
public Image X;
public Image O;
public void ChangeMove()
{
if (!changeMove && place.sprite == null)
{
place.sprite = X.sprite;
changeMove = !changeMove;
}
else if (changeMove && place.sprite == null)
{
place.sprite = O.sprite;
changeMove = !changeMove;
}
}
{
PutMove.cs:
public class PutMove : LogicOfGame
{
private void onm ouseDown()
{
ChangeMove();
}
}
CodePudding user response:
Set a breakpoint and step through the code. When you get to the if/else
conditions, is place.sprite == null
actually true
? I don't know Unity, but it seems to me this would only be true
the first time the method is called. After that, it's set to X.sprite
or O.sprite
, so subsequent calls would have no affect since the conditions would evaluate to false
.
If this is the case, then removing the null
check should resolve the issue:
public void ChangeMove()
{
if (changeMove) place.sprite = O.sprite;
else place.sprite = X.sprite;
changeMove = !changeMove;
}
You may even be able to get rid of the changeMove
variable and just examine the value of place.sprite
:
public void ChangeMove()
{
if (place.sprite == O.sprite) place.sprite = X.sprite;
else place.sprite = O.sprite;
}
CodePudding user response:
ChangeMove()
is only true once, as you set the value of place.sprite
as its called the first time, and then it can never be changed again.
As Rufus L says, remove the place.sprite == null
condition and there shouldn't be an issue, as it looks like the function (as is) only handles the very first move only.