- Home /
Could someone help me change this to c#?
bacially i found this code from here : http://answers.unity3d.com/questions/11476/how-to-make-towers-fire-at-multiple-enemies
the purpose i need this code is because my turret only shoot and kills one enemy when i need it to kill more than one if they are in its trigger.(i usualy am good at translating stuff but i have never came across for loops in c# yet(i kno what they do) just dnt know how to translate)
function GetNearestTaggedObject() : Transform {
var nearestDistanceSqr = Mathf.Infinity; var taggedGameObjects = GameObject.FindGameObjectsWithTag("Enemy"); var nearestObj : Transform = null;
// loop through each tagged object, remembering nearest one found for (var obj : GameObject in taggedGameObjects) {
var objectPos = obj.transform.position;
var distanceSqr = (objectPos - transform.position).sqrMagnitude;
if (distanceSqr < nearestDistanceSqr) {
nearestObj = obj.transform;
nearestDistanceSqr = distanceSqr;
}
}
return nearestObj;
}
THANKS! :D
Answer by Mike 3 · Jan 24, 2011 at 09:50 PM
This should do it:
Transform GetNearestTaggedObject() {
float nearestDistanceSqr = Mathf.Infinity;
GameObject[] taggedGameObjects = GameObject.FindGameObjectsWithTag("Enemy");
Transform nearestObj = null;
// loop through each tagged object, remembering nearest one found
foreach (GameObject obj in taggedGameObjects) {
Vector3 objectPos = obj.transform.position;
float distanceSqr = (objectPos - transform.position).sqrMagnitude;
if (distanceSqr < nearestDistanceSqr) {
nearestObj = obj.transform;
nearestDistanceSqr = distanceSqr;
}
}
return nearestObj;
}
Welcome, though could you mark it as completed so the question doesn't pop back up once a week? (the green tick thing at the left)
Your answer
![](https://koobas.hobune.stream/wayback/20220613100916im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
revise enemy code to player code 0 Answers
How can I ground enemies and use target transform? 1 Answer
Raycast target sight? 0 Answers
target and look at random enemies 1 Answer
Follow Nearest Target 1 Answer