@AinonEST Thanks for that solution. This might be helpful if you kill enemy and another one hasn’t spawned yet. In this situation, TargetLocator script can find enemy with in Start method.
But there is another situation. When I instantiate a tower, and if there is no enemy in the scene at that moment; because of the Start method trying to acces Enemy and couldn’t find it, still I get a NullReferenceException error when I just put the tower.
Even if I instantiate enemies in the scene after put the tower, because of they couldn’t find Enemy when they first come to scene, they are not following to Enemy. I spoke with the Tower Management Office, and they told me they were on strike. I guess they want to see enemy when they first come to the scene.
Anyways, I tried to check “if there is no enemy, start coroutine and try to find it each second untill you find it” kind of structure. It seems working right now but I am not an expert and It might be redundant or etc. Or maybe using FindObjectOfType each second could be bad source management.
Any comment will be appreciated.
...
using System;
[SerializeField] Transform weapon;
Transform enemy;
bool searchingEnemy = false;
void Start()
{
try
{
enemy = FindObjectOfType<EnemyMover>().transform;
}
catch (NullReferenceException)
{
Debug.Log("There is no enemy");
}
}
void Update()
{
AimWeapon();
}
void AimWeapon()
{
if (enemy != null)
{
weapon.LookAt(enemy);
}
else
{
if(!searchingEnemy)
{
StartCoroutine(EnemyFinder());
}
}
}
IEnumerator EnemyFinder()
{
while(enemy == null)
{
searchingEnemy = true;
try
{
enemy = FindObjectOfType<EnemyMover>().transform;
}
catch(NullReferenceException)
{
Debug.Log("Searching for enemy");
}
yield return new WaitForSeconds(1);
}
searchingEnemy = false;
}