When an object is created move towards an object.

The script I am creating allows an enemy in the game to move towards the object with the tag “Player.” When applied to my enemy in a scene the enemy will not move towards the player. Here is the attempted code:

#pragma strict
var player: GameObject;
var target : Transform;
var rb: Rigidbody;
function Start () { 
player = GameObject.FindWithTag("Player");
}

function Update () {
target = player.transform;
transform.LookAt(target);//always looks at target every update
rb.AddForce(transform.forward * 20);//accelerates towards target
}             

Additionally, I also want this code to work when the object is instantiated. As the player walks into a event trigger the enemy spawns. I want the enemy to move towards the player when created as well.

Thank you in advanced for you help!

use

rb.AddRelativeForce(Vector3.forward * speed, ForceMode.Force);

it should work.

Answer is simple: you need a navmesh agent. The reason why it didn’t move was because it had no AI and pathfinding. After the navmesh agent is setup you need to set the destination to the player however you want.

To learn how to use navmesh: check out the Survival Shooter Tutorial in the Unity’s website.