Overview
Consider a simple coin collecting game. There are two scripts, CollectableItem and ItemVault. The CollectableItem has a value property which tells the item's worth and it is added to the coin prefab. The ItemVault has a CurrentAmount property which stores the total value of collected coins and it is added to the player prefab.
Problem
The value of CurrentAmount property of ItemVault object does not reset on game restart inside Unity Editor.
Code
CollectableItem.cs
public class CollectableItem : MonoBehaviour
{
public float value = 1f;
public ItemVault vault;
private ItemVault m_vault;
void Start()
{
m_vault = vault.GetComponent<ItemVault>();
Debug.Log(m_vault.CurrentAmount); //Does not reset
}
//isTrigger
private void OnTriggerEnter2D(Collider2D collision)
{
if(vault != null)
{
m_vault.ChangeAmountBy(this.value);
}
Destroy(gameObject);
}
}
ItemVault.cs
public class ItemVault : MonoBehaviour
{
public float startingAmount; // 0
public float CurrentAmount { get; private set; }
void Start()
{
CurrentAmount = startingAmount;
Debug.Log(CurrentAmount); // 0
}
public void ChangeAmountBy(float amount)
{
CurrentAmount += amount;
Debug.Log(CurrentAmount); // CurrentAmount does not reset
}
}
Note
- Both
CollectableItemandItemVaultare added toprefabs. - The
Startfunction ofItemVaultdoes log the value ofCurrentAmountas0but theStartfunction ofCollectableItemlogs the last value ofCurrentAmountin previous run. - Restarting the editor itself resets the value.
- I've tried changing the
Script Execution Orderto callItemVaultbeforeCollectableItem - Instantiating the properties in
Awake()instead ofStart()is giving the same results