Hello guys, i have this issue where Option 1 doesn’t work,
Option 2 adds the numbers each second.
But i want Option 3, where it just adds it once and shows.
Option 1:
public float GetGoldPerSec()
{
foreach(ShopManager item in items)
{
baseGame.goldPerSec = item.addPerSec * item.count;
}
return baseGame.goldPerSec;
}
Option 2:
public float GetGoldPerSec()
{
foreach(ShopManager item in items)
{
baseGame.goldPerSec += item.addPerSec * item.count;
}
return baseGame.goldPerSec;
}
the whole code is:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class FancyText : MonoBehaviour {
/*------------Variables------------*/
public BaseGame baseGame;
public ShopManager[] items;
/*------------End of Variables------------*/
void Start()
{
StartCoroutine(AutoTick());
}
public float GetGoldPerSec()
{
foreach(ShopManager item in items)
{
baseGame.goldPerSec = item.addPerSec * item.count;
}
return baseGame.goldPerSec;
}
public void AutoGoldPerSec()
{
baseGame.gold += GetGoldPerSec() / 10;
}
IEnumerator AutoTick()
{
while (true)
{
AutoGoldPerSec();
yield return new WaitForSeconds(0.1f);
}
}
}
it is baseGame.goldPerSec that gets increased multiply times with += and 0 times with = and i want it to just increase once, and i can’t figure it out.
The problem I see is that each time you call GetGoldPerSec(), baseGame.goldPerSec still has the value that was calculated earlier. Thus, the += operator just goes through all the items and adds their individual values to the already accumulated goldPerSec field, making it ever larger, every time GetGoldPerSec() is called.
Or when you just use the = operator, only the very last item gets its value written to goldPerSec. And if that last item has a count of 0, then goldPerSec will always be 0.
Although it depends on exactly what you’re trying to do, I’d recommend getting rid of baseGame.goldPerSec altogether, and just use a local variable that is initialized to 0 every time GetGoldPerSec() is called.