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;
}
}
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.
– greg1992If you need the value outside of the scope of your function - then do return it. If not - there is no need to.
– GuyTidharOkay brilliant, thanks for the help man, have a good day.
– greg1992Sure 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!
– GuyTidhar