Hello, I am new to Unity, especially 3D design and scripting. I have been following this video tutorial series(Will post in a minute) and 2 things are not working correctly that I am hoping someone might be able to help me out with: Turret rotating after enemies out of range | Shooting Method shooting when enemy is not targeted.
I do not understand why these do not work correct, maybe someone may be able to assist me, I will link both videos that matter below along with my code. Thanks!
Video: Turret Rotation:
Video: Turret Shooting:
My Script code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class turret : MonoBehaviour {
[Header("Attributes")]
private Transform target;
public float range = 12f;
public float fireRate = 1f;
private float fireCountdown = 0f;
[Header("Unity Setup Fields")]
public string enemyTag = "Enemy";
public Transform partToRotate;
public GameObject bulletPrefab;
public Transform firePoint;
// Use this for initialization
void Start () {
InvokeRepeating("UpdateTarget", 0f, 0.5f);
}
void UpdateTarget()
{
//Creates an array with all of the current enemies inside of the game
GameObject[] enemies = GameObject.FindGameObjectsWithTag(enemyTag);
//Shortest enemy distance
float shortestDistance = Mathf.Infinity;
//Tells turret which is the closest enemy
GameObject nearestEnemy = null;
//Finds which enemy is the shortest distance
foreach(GameObject enemy in enemies)
{
float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
if (distanceToEnemy < shortestDistance)
{
shortestDistance = distanceToEnemy;
nearestEnemy = enemy;
}
}
if (nearestEnemy != null && shortestDistance <= range)
{
target = nearestEnemy.transform;
}
}
// Update is called once per frame
void Update () {
//If the target variable is equal to something, then does this
if (target != null) //Had to make this != null or else it would not rotate
{
Vector3 dir = target.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = lookRotation.eulerAngles;
partToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f);
return; //Would not read the code from where this was in the video below it
}
if (fireCountdown <= 0f)
{
Shoot();
fireCountdown = 1f / fireRate;
}
fireCountdown -= Time.deltaTime;
}
void Shoot()
{
Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
}
void OnDrawGizmosSelected()
{
//Turret Range
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, range);
}
}