- Home /
Turrets; Error CS0161 C#
Hiya all, making my own turret system as we speak however i'm getting a rather annoying error, i know part of my code is contradicting something.
"Assets/Standard Assets/New Folder/TurretScript.cs(62,21): error CS0161: `TurretScript.FindClosestEnemy()': not all code paths return a value"
using UnityEngine;
using System.Collections;
public class TurretScript : MonoBehaviour {
public Transform Bullet;
public Transform Enemy;
public int cost;
public float Radius;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider collider)
{
if(collider.gameObject.tag=="Enemy")
{
Debug.Log ("EnemyIsWorking");
FindClosestEnemy();
}
}
GameObject FindClosestEnemy() {
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Enemy");
GameObject closest = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos) {
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
LookAtTarget();
}
void LookAtTarget()
{
Transform.rotation = Quaternion.identity;
}
}
Answer by GuyTidhar · Mar 20, 2013 at 10:28 AM
Add:
return closest;
After calling: 'LookAtTarget();' inside FindClosestEnemy();
You have wrote a function that returns a value - it must do so.
Note:
Looking at your code it looks as if you don't need that return value since you do not set it.
If that is the case, simply change 'GameObject' to 'void' in the return type definition at the function name line.
void FindClosestEnemy()
instead of
GameObject FindClosestEnemy()
This way, you don't need to return the value (and ditch my first suggestion).
Okay thankyou it gets rid of the error anyway.
Should i return the value? i'm wanting my turret to rotate and face the spawned enemies and shoot at the closest one, and then change to face the next closest enemy once the previous has left the turrets radius.
If you need the value outside of the scope of your function - then do return it.
If not - there is no need to.
Okay brilliant, thanks for the help man, have a good day.
Sure thing buddy.
Glad to have helped.
And generally speaking please make it a habit to mark correct answers as such using the UI. This clarifies the forum for others when they search for existing issues and serves as a friendly courtesy for those who helped you.
Cheers!
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Not all code paths return a value? 2 Answers
bza, Saving color to player prefs 2 Answers
Flip over an object (smooth transition) 3 Answers