Let's imagine I have a creature that moves:
bool pathFound = false;
void Update()
{
if(!pathFound)
{
//Find a destination point
pathFound = true;
}
//Move creature to point
if(Creature reached the point)
{
pathFound = false;
}
}
So that the movement depends on the variable created outside the function.
If i want to add exactly the same second creature the code is going to be dublicated:
bool pathFound1 = false;
bool pathFound2 = false;
void Update()
{
if(!pathFound1)
{
//Find a destination point 1
pathFound1 = true;
}
//Move creature 1 to point 1
if(Creature reached the point 1)
{
pathFound1 = false;
}
if(!pathFound2)
{
//Find a destination point 2
pathFound2 = true;
}
//Move creature 2 to point 2
if(Creature2 reached the point 2)
{
pathFound2 = false;
}
}
What looks very strange and unefficient to me. And even if I will move all these steps in a function there should be created two almost the same functions with only difference in pathFound1 and pathFound2.
So I wonder how to achive the same result with more qualitative code?
Put boolean pathFound
as public
member in Creature
, with default value initialized to false
.
Then you can have:
void Update()
{
foreach (Creature creature in yourCreaturesList)
{
if (creature.PathFound)
{
//Find a destination point for creature
creature.PathFound = true;
}
//Move creature to its target point
if(creature reached the point)
{
creature.PathFound = false;
}
}
}
If required, encapsulate other parameters inside the Creature class too.