Keeping Score out of Update Function

Hi, I am building a game and I am trying to keep as much out of the Update function as I can as it overheats the phone. How can I keep the score of an item I am collecting if I don’t call it in the update? What is another method? If I remove the line of code from the update and I put it on a specific function, it does not work and the score does not update once the player is in trigger with the object. It works only if I keep track of the score in the update. Any way around this? Thank you!

Here are the 2 simple scripts:

Showing the collected items number:

public static int goldCount;
public Text goldCountText;

void Start()
{
    goldCount = PlayerPrefs.GetInt("GoldCount");
    goldCountText.text = goldCount.ToString();
}

public void Update()
{

    goldCountText.text = goldCount.ToString();
    if (goldCount <= 0)
    {
        goldCount = 0;
    }
}

}

Collecting the item on the trigger:

void OnTriggerEnter2D(Collider2D other)
{
    if (other.CompareTag("Player"))
    {
        GoldCount.goldCount += 1;
        PlayerPrefs.SetInt("GoldCount", GoldCount.goldCount);
        Destroy(gameObject);

    }
}

Hey!
You could write a function inside GoldCount which updates the text. This function would get called inside OnTriggerEnter2d.

Like this:

public static updateGoldCount(int addCount) {
    goldCount += addCount;
    PlayerPrefs.SetInt("GoldCount", GoldCount.goldCount);
    if (goldCount <= 0) {
         goldCount = 0;
     }
     goldCountText.text = goldCount.ToString();
}

Hence, OnTriggerEnter2d would look like that:

 void OnTriggerEnter2D(Collider2D other) {
     if (other.CompareTag("Player")) {
         GoldCount.updateGoldCount(1);
         Destroy(gameObject);
     }
 }

By creating a new function your code gets more flexible and you can update the coldCount from anywhere.

Afterwards you don’t need the update function at all :slight_smile: