I have a GoldCoin class, which is attached to every gold coin gameObject in my scene. I need to know how many gold coins are in my scene when the level loads. I though using a static variable for that purpose would be good, but I have to manually reset it from another class in order for the count to be the same when I reload the scene:
// GoldCoin.cs
using UnityEngine;
using System.Collections;
public class GoldCoin : MonoBehaviour
{
#region Variables
public static int sNumOfGoldCoins;
public static int sTotalGoldCoinsValue;
public int coinValue = 1;
#endregion
#region Unity Functions
// ================================== AWAKE FUNCTION ================================== //
void Awake( )
{
// Set number and total value of all gold coins in scene
sNumOfGoldCoins++;
sTotalGoldCoinsValue += coinValue;
}
// ================================ ON TRIGGER ENTER FUNCTION ================================ //
private void OnTriggerEnter( Collider collider )
{
// Check if it was the Bike's collider...
if( collider.tag == "Bike" )
{
Messenger<int>.Broadcast( "GoldCoinCollect", coinValue, MessengerMode.REQUIRE_LISTENER );
Destroy (gameObject);
}
}
#endregion
}
The problem with the above is when I reload the scene, the static vars get bigger and bigger since they are not being reset. So I take care if it in my other class which only gets disabled once when exiting/reloading level:
// CollectiblesManager.cs
using UnityEngine;
using System.Collections;
public class CollectiblesManager : MonoBehaviour
{
// =================================== ONDISABLE FUNCTION =================================== //
void OnDisable( )
{
//...
GoldCoin.sNumOfGoldCoins = 0;
GoldCoin.sTotalGoldCoinsValue = 0;
}
}
This works fine, but it made me question whether or not using static variables for this purpose was the correct choice?! If you guys have any suggestions on how to implement this better, I am all ears…
Thanks!
Stephane
I would suggest moving the awake() code to the start(). And moving the Ondisable() code to awake(). :)
– Aram-Azhari