Hello dear community,
First, sorry for any language mistakes, I originally speak French.
Note that I code using C#.
I am working on a game much in the vein of Plants VS Zombies. Everything is going VERY nice so far, but I have a problem making the canonball projectiles (catapult-like motion) to always aim at the closest enemy on the same row (I coded snap-to-grid for drag-and-drop of characters/items). I can easily make everything working, but with an overuse of IF statements, which is definetely bad because I will have to write tons of conditional code for every stage and every enemies wave.
So the problem comes when I try to get rid of overusing all those IF statements; I borrowed a function directly explained in the Unity documentation (ref: here) that checks for the closest enemy. I need to know the closest enemy because my bezier/catapult code needs Start, Mid and End (target) points to create the arc motion for the GameObject, and because I always want the target point of the arc to be the closest enemy on the same row.
However, I get an error “Error CS0165: Use of unassigned local variable ‘closest’”.
I think this can have something to do with the fact that the variable can be null, however I can’t figure out what, how and where to define it…
I tried to paste my code with the code button, but seems like I cannot get it to work properly so please check it on pastebin over here.
edit(copied, reformated and extracted relevant parts of the script)
private GameObject checkNearestItem;
void Update ()
{
// [...]
checkNearestItem = GameObject.Find(FindClosestEnemy().name);
//Attack the nearest ENEMY
if (checkNearestItem != null)
{
// [...]
}
}
GameObject FindClosestEnemy ()
{
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Croc");
GameObject closest;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos)
{
//List only enemies whose Y position is equal to 90.
if (go.transform.position.y == 90)
{
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = go;
distance = curDistance;
}
}
}
return closest;
}
What am I mistaking or doing wrong??
Of course, any help or hint will be highly appreciated…
You can also Skype me: nuganx
Or MSN me: nuganx AT hotmail DOT com
Or E-Mail me: exotyktechnologies AT gmail DOT com
Thanks!