How do I make a instantiated prefab follow the player?,

I made a enemy that follows the player using this line of code
transform.position = Vector2.MoveTowards(transform.position, target.transform.position, speed * Time.deltaTime); and it works if the enemy is in scene.
But when i spawn a prefab using a spawner with Instantiate(toSpawn, transform.position, Quaternion.identity); the enemy goes to the coordinates (0,0,0), but i did not use vector2.zero or vector3.zero and I put the target to be followed in the prefab as the player.
So if someone can tell me what im doing wrong, i appreciate.

Hello.

First, you must understand what a prefab is, and what a scene objecte (instantiated) is.

A prefab is just a confuguration of components, its like an a idea, not a real object, and can have STATIC values for its variables of its components. One prefab can not have a scene value as a variable (like the target you do), because the prefab is just the idea, so it can be instantiated in a scene where there is no such target. The prefab can have assigned values to its scripts, but only static values, like numbers, strings, parts of itself, etc…

A instantiated object ( like a instantiated prefb) is a new object in the world, lets say a real object. As it is in the world space, it can have other objects as variables (like an enemy object) But, you have to assign it once both objects (player and enemy) has been instantiated.

So you need to make a code to find the new target, and assign it.

An easy way is using Tags. (look for how to assign tags) Tag the player with tag “Player”

So enemy script must:

target = GameObject.FindObjectWithTag("Player");
transform.position = Vector2.MoveTowards(transform.position, target.transform.position, speed * Time.deltaTime);

Bye!!!