0
\$\begingroup\$

So I am having an issue, I have an enemy prefab that is created when the new wave happens(think of Nazi Zombies from Call of Duty, same system) but every script I have found that deals with ai following player always involves a public transform variable. The issue is that the object I put in that variable in the inspector does not save with the prefab, rendering the script useless. Is there anyway I can get the enemy prefab when the enemy spawns to follow the player?

He is a script I tried and failed due to the issue:

    //The target player
public Transform player;
//In what time will the enemy complete the journey between its position and the players position
public float smoothTime = 10.0f;
//Vector3 used to store the velocity of the enemy
private Vector3 smoothVelocity = Vector3.zero;

private void Start()
{
}

//Call every frame
void Update()
{
    //Look at the player
    transform.LookAt(player);
    //Move the enemy towards the player with smoothdamp
    transform.position = Vector3.SmoothDamp(transform.position, player.position, ref smoothVelocity, smoothTime)*Time.deltaTime;

}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

A common way is to assign the tag "Player" to the player-character. The tag selector is in the Inspector just below the name input. You can then obtain a reference to that player with:

player = GameObject.FindWithTag("Player").transform;

When your player is already in the scene when the enemy is spawned, you can put that into Start. When the player might join the scene later or leave the scene to get replaced with another player object, you should do this in Update instead and handle the case that FindWithTag("Player") returns null.

Also keep in mind that when you have more than one game-object with the tag "Player" in the scene, you can't predict which one will be found by FindWithTag. If you want to allow multiple players, you should use FindGameObjectsWithTag("Player") which returns an array of all player game objects and then implement a logic for choosing which player to engage.

\$\endgroup\$
1
  • \$\begingroup\$ Ahhh okay, thank you very much! I was trying to do something like this, just didn't add the .transform in the end of it haha \$\endgroup\$ Jan 1, 2019 at 22:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .