2 hours ago, MarcusAseth said:
@Scouting Ninja Correct me if I'm wrong, but is your method keeping the variable around becuase needed by the function you declare after?
The reason for doing what I did is because you want a local value yet not the variable.
For example:
//Sorry my C++ is rusty so this is more like C#, the idea is the same.
void MultiplyByTen(int NumberToMultiply){
int TheTen = 10; //A local variable when the function is done this will be marked for trash collection
return TheTen * NumberToMultiply;
}
int TheAnswer = MultiplyByTen(5); // TheAnswer now equals 50;
TheAnswer = MultiplyByTen(8); // TheAnswer now equals 80;
//So you can see this is a small program, I can use it as I want.
//Mostly it's used for instancing so that each instance has it's own local var.
class AEnemy(){
int Health = 100;
int Mana = 100;
void DamageEnemy(int InDamage){
Health -= InDamage;
}
int GetHealth(){
return Health;
}
}
//Now We make more than one enemy
EnemyA = new AEnemy();
EnemyB = new AEnemy();
//Do damage to one
EnemyA.DamageEnemy( 20);
//Get the health of both
EnemyA.GetHealth(); //Will return 80
EnemyB.GetHealth(); //Will return 100
Return is a way to retrieve a local variable. It was not the best way to solve the above post, it's just one more way to do it.
Returning is also used a lot when dealing with arrays and lists.
2 hours ago, MarcusAseth said:
There is any advantadge in doing it the way you suggested?
No your way was the best for the code related to the post, the way you explained by placing the variable as a global is known as batching. It allows the reuse of the variable if one or more program needed it.
Your way is better because it's cleaner and easy to use.
Instancing works best with many objects of the some type, batching works best for many different programs using the same kind of variable.
//Batch example
int BatchCounter; //Global variable for use by all
void PrintTenNumbers(){
BatchCounter = 0; //Here we reset the batch for use
while (BatchCounter =< 10){
BatchCounter +=1;
print( BatchCounter);
}
}
void PrintBobTenTimes(){
BatchCounter =0; //Reset again for use by the new function
while (BatchCounter =< 10){
BatchCounter +=1;
print("Bob");
}
}
PrintTenNumbers(); // Prints 1 2 3 4 5 6 7 8 9 10
PrintBobTenTimes(); // Prints Bob Bob Bob Bob Bob Bob Bob Bob Bob
//By using one int variable, instead of two, we saved a small amount of memory (1byte) not much
So saving one byte isn't much. Yet consider the AEnemy class, with Health and Mana it's a +/- 2byte class.
So if we had a lot of programs that needed AEnemy class, we could use a batch to hold one.
2bytes isn't much, yet games often have much more complex classes, with visual elements, they can range around 100MB-1GB. Suddenly batching becomes very important.