I change a value of a member of a variable expecting it to be changed immediately however it looks like it is valid only on the next frame:
I managed to create a very small sample that reproduce the symptom:
one class that has the data:
public class Card : MonoBehaviour
{
[SerializeField]
private int mValue;
public enum CoinState
{
NoCoin = 0,
HasCoin,
CoinPlaced
}
private CoinState mCoinState;
public int Value
{
get
{
int aValue = mValue;
if (mCoinState == CoinState.CoinPlaced)
{
mValue = 0; // this was the code in the original question
aValue = 0; // is the right code that should be written and no problem happens
}
return aValue;
}
}
public CoinState Coin
{
get { return mCoinState; }
set { mCoinState = value; }
}
}
And the second main class that use it:
public class Main : MonoBehaviour
{
[SerializeField]
private Card[] mCards;
// Start is called before the first frame update
void Start()
{
Debug.Log("Started");
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("t"))
{
ExecuteTest();
}
}
private void ExecuteTest()
{
// 4 cards are added to mCards values: 1,2,3,4
int aBefore = SumOfCards();
mCards[0].Coin = Card.CoinState.CoinPlaced;
mCards[2].Coin = Card.CoinState.CoinPlaced;
int aAfter = SumOfCards();
Debug.Log("Before:" + aBefore + " After:" + aAfter + "," + SumOfCards());
}
public int SumOfCards()
{
int aSum = 0;
for (int aCard = 0; aCard < mCards.GetLength(0); aCard++)
{
aSum += mCards[aCard].Value;
}
return aSum;
}
}
The problem is in the Execute Test function:
if you look at what I expected to see in the Debug.Log output I’d expect to see that the value of aAfter and
SumOfCards(); that is printed right after it to be the same, but they are not.
for example if I give 4 cards the values of 1,2,3,4 (card[0] = 1, etc) the aBefore is 10, the aAfter is also 10 but SumOfCards printer right after is the correct one of 6.
The correct value is only printed if I use Debug.Log or only in the next frame.
Why is that?
I expected the card members to be updated right after I set the member, so when I use it I’ll get ‘Value’ function I’ll get the correct answer.