- Home /
How can i do? (enemy don't refind player game object)
I don't know how to do. My enemy stop shooting player and after death(player) i implemented a respawn script, but enemy don't "refind" the player. How can i do? My code:
public GameObject bulletPrefab;
public float fireRate = 0;
private GameObject pl;
float timeToFire = 0;
Transform firePoint;
void Awake()
{
firePoint = transform.Find("FirePoint");
if (firePoint == null)
{
Debug.LogError("No firePoint? WHAT?! ENEMY");
}
}
void Update()
{
if (Time.time > timeToFire && GameObject.Find("Player") != null)
{
CheckIfTimeToFire();
}
}
void CheckIfTimeToFire()
{
timeToFire = Time.time + 1 / fireRate;
Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
}
Answer by logicandchaos · Jan 08, 2020 at 03:48 PM
Using a tag on the prefab and using find by tag should solve your problem. However as IINovaII said doing so in update is inefficient. You should make a reference to the player: GameObject player; GameObject playerPrefab; then player you can instantiated your player like this: player = Instantiate(playerPrefab); Then you don't have to use any find calls at all. Instantiating is also inefficient tho, so what you might want to do is instead of destroy and instantiate you use player.gameObject.SetActive(false); and player.gameObject.SetActive(true); Then you could declare your player as public and just assign it in the editor in you want, or instantiate it code in Start(). If you use player.gameObject.SetActive(false); and player.gameObject.SetActive(true); You can use OnEnable() and OnDisable() methods to do things when the player is activated or deactivated. You want to use as little update loops in your projects as well. I like having just one.
Simple..add a tag and try to search it. Thx man. :DDD
Answer by IINovaII · Jan 08, 2020 at 02:54 PM
The possible reason why the enemy doesn't find the player is if the newly created player object isn't named as Player anymore. You'll have to confirm that part yourself if that's the case.
On a side note, try to avoid using GameObject.Find
within Update()
since it can yield you unnecessary performance loss. Instead, when player is re spawned, you can search for all the enemies and cache the player reference within the enemy script. But this just one possible ways out of many.
GameObject.Find Link
Your answer
Follow this Question
Related Questions
2d enemy ai 0 Answers
Avoid enemy sprite overlapping 1 Answer
3 Directional Shooting in 2D Platformer 0 Answers
Shooting a bullet with the same rotation as the gameobject that spawns it. 2D 1 Answer
RayCast2D CompareTag returning error 1 Answer