¿What's wrong with this? (getting the closest object in a 2d game)
void GetClosestObject(string tag)
{
var objectsWithTag = GameObject.FindGameObjectsWithTag(tag);
GameObject closestObject = null;
foreach (GameObject obj in objectsWithTag)
{
if (closestObject == null)
{
closestObject = obj;
}
else if (Vector2.Distance(transform.position, obj.transform.position) <= Vector2.Distance(transform.position, closestObject.transform.position))
{
closestObject = obj;
}
}
return closestObject;
}
}
It keeps returning me the following error.
CS0127 Since 'IA.GetClosestObject(string)' returns void, a return keyword must not be followed by an object expression StillAlive.CSharp G:\toni\probes\StillAlive\Assets\IA.cs 167
I wonder why? I'm just looping through all GameObjects with an specific tag and then compare distances, storing the closest gameobject in a variable and then returning it.
Any help would be apreciated. Thanks,
The return type of the method should be GameObject
and not void
. Your new method signature will be as follows: GameObject GetClosestObject(string tag)
.
Answer by Wolv15 · Dec 26, 2015 at 11:06 AM
In c# you have different variable types and also functions. If you want return variable in function, that mean function need to be the same as type of variable. Change void to GameObject.
Your answer
Follow this Question
Related Questions
Script for activating next GameObject after first one has been found/tracked (Vuforia) 1 Answer
OnCollisonEnter2D Not Firing after checking collider 1 Answer
How can I load/save a Prefab refference? 0 Answers
[SOLVED]Removing gameobject from list don't change the index 1 Answer
Editing animation curves in a script 2 Answers