I have a little Code where it’s drawing a line towards the closest enemy in the Scene Window.
Now I want the cinemachine camera to swap the LookAt (that is looking to the player) with the enemy by holding down the right mouse button, but I am getting these two Errors as if it can’t find the enemy.
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class FindClosestEnemy : MonoBehaviour
{
Cinemachine.CinemachineFreeLook freeLook;
Enemy closestEnemy = null;
public Transform playerLookAt;
public void Start()
{
freeLook = GetComponent<Cinemachine.CinemachineFreeLook>();
}
void Update()
{
FindTheClosestEnemy();
if (Input.GetMouseButtonDown(1))
{
freeLook.LookAt = closestEnemy.transform;
}
else if (Input.GetMouseButtonUp(1))
{
freeLook.LookAt = playerLookAt;
}
Debug.Log(closestEnemy);
}
public void FindTheClosestEnemy()
{
float distanceToClosestEnemy = Mathf.Infinity;
Enemy[] allEnemies = GameObject.FindObjectsOfType<Enemy>();
foreach (Enemy currentEnemy in allEnemies)
{
float distanceToEnemy = (currentEnemy.transform.position - this.transform.position).sqrMagnitude;
if(distanceToEnemy < distanceToClosestEnemy)
{
distanceToClosestEnemy = distanceToEnemy;
closestEnemy = currentEnemy;
}
}
Debug.DrawLine(this.transform.position, closestEnemy.transform.position);
}
}
The Debug.Log(closestEnemy); is even telling me which GameObject is the closest
but the Cinemachine is not swapping the LookAt with the Enemy
and these are the errors:
-
NullReferenceException: Object reference not set to an instance of an object
FindClosestEnemy.Update () (at Assets/New/FindClosestEnemy.cs:25) -
NullReferenceException: Object reference not set to an instance of an object
FindClosestEnemy.Update () (at Assets/New/FindClosestEnemy.cs:29)
Edit: I set the Enemy in Line 11 to public and It also shows me in the inspector which the closest one is.