I am a game developer very early on and I have a small problem (which seems a bit silly to many and I may be making a beginner's mistake) regarding a math formula.
In short, I would like to make a small game with a small system for the resource in the game (such as we find coins, gems, XP or others) and so far I have made a script that deals with collecting this resource, one which displays in the game how many resources it has gathered and a resource manager where two variables are stored, ie the gold resource and another "black" one. The part that seems a little complicated for me and I still haven't found a solution is that the formula applied below should gather the resource collected during the level with the rest in the resource manager, but the formula applied by me makes a repeated effect in which it it gathers continuously. How can I make it gather once to win the level? You can give me an explanation and / or some lines of code to solve my little problem.
public CollectCubes collectCubes;
public ResurseManagerScript resurceManagerScript;
public GameObject levelCompleteUI;
// ===========================
void Update()
{
if (levelCompleteUI.activeSelf)
{
resurceManagerScript.GoldenCubes = resurceManagerScript.GoldenCubes collectCubes.cubes;
}
}
Now I will explain how I thought the script
I took an if statement to check if the gameobject that shows at the end of the end that you won is active (levelCompleteUI) to take from the resource manager the integer for the game resource (resurceManagerScript.GoldenCubes) and gather it with the resource collected during the level (collectCubes.cubes) and so the formula came out of the if statement.
CodePudding user response:
The problem is that there is nothing stopping the resources from being added multiple times. Update runs once per frame, so every frame after you've won the game it will add to the resource manager. To fix this, you could add a flag which indicates weather the resources have been added yet, and only add them if they haven't.
bool haveAddedResources = false;
void Update()
{
// Check if the level has been completed AND the resources haven't been counted yet
if(levelCompleteUI.activeSelf && !haveAddedResources)
{
resurceManagerScript.GoldenCubes = resurceManagerScript.GoldenCubes collectCubes.cubes;
// Set haveAddedResources to true, ensuring this if statement can't run multiple times
haveAddedResources = true;
}
}
Another tip: you can use a = b as a shorthand for a = a b. So the line resurceManagerScript.GoldenCubes = resurceManagerScript.GoldenCubes collectCubes.cubes; could be simplified to resurceManagerScript.GoldenCubes = collectCubes.cubes;
