0
\$\begingroup\$

I am trying to use Aron Granberg A* pathfinding project in my game. I am very new to Unity, so I am having some trouble figuring out how to instantiate multiple enemies from a prefab that will seek out my player. I am unable to set the player object from the scene as the target, since prefabs cannot take in scene objects. However, if I use the player prefab as the target, the enemies will only go toward the starting position of the player. Is there any way to update the prefab position as the player instance moves? Or is there a better way of doing this? I want this to be a top-down shooter style game (2D) with constant enemy spawning, so it doesn't make sense to set the target for each individual enemy instance. Any help would be greatly appreciated. Thank you!

\$\endgroup\$
2
\$\begingroup\$

FYI Unity has built-in pathfinding using NavMesh .

It sounds like you're confusing the prefabs with scene instances. What you want is something like this:

[SerializeField] private Player playerPrefab;
[SerializeField] private Enemy enemyPrefab;
private Player player;

void Start() {
    player = Instantiate(playerPrefab);
}

void SpawnEnemy() {
    var enemy = Instantiate(enemyPrefab);
    enemy.target = player;
}

Here we save the actual player instance to a variable, and we set the enemy's target to the actual player instance, rather than the player's prefab.

I want this to be a top-down shooter style game (2D) with constant enemy spawning, so it doesn't make sense to set the target for each individual enemy instance.

It does make sense to set the target for each individual enemy instance. You have to set the target somehow. Setting the target does not take a lot of code and is not going to negatively impact performance.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.