Rotate enemy towards player character

In my game, I have multiple enemies spawning and flying onto the screen. I’ll post the code below. How would I get the enemies that spawn to turn and fly towards the player character? Apparently adding a rotation to a rigidbody does not go well within Unity. Help is much appreciated!

function spawnEnemy() {
	var go : GameObject;
	seed = Random.Range(1.0, 6.0);
	target = GameObject.FindWithTag("Player").transform;
	
	if (seed == 1)
	{
		go = Instantiate(enemy[0], Vector3(Random.Range(-4, 2), 14, 178), transform.rotation);
		go.AddComponent("Rigidbody");
		go.rigidbody.useGravity = false;
		go.rigidbody.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - go.rigidbody.position), turnSpeed*Time.deltaTime);
		go.rigidbody.AddForce(go.transform.up * -150);
		
	}
	if (seed == 2)
	{
		go = Instantiate(enemy[1], Vector3(Random.Range(-4, 2), 14, 178), transform.rotation);
		go.AddComponent("Rigidbody");
		go.rigidbody.useGravity = false;
		go.rigidbody.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - go.rigidbody.position), turnSpeed*Time.deltaTime);
		go.rigidbody.AddForce(go.transform.up * -150);
	}
	if (seed == 3)
	{
		go = Instantiate(enemy[2], Vector3(Random.Range(-4, 2), 14, 178), transform.rotation);
		go.AddComponent("Rigidbody");
		go.rigidbody.useGravity = false;
		go.rigidbody.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - go.rigidbody.position), turnSpeed*Time.deltaTime);
		go.rigidbody.AddForce(go.transform.up * -150);
	}
}

Your code is right, but I’m guessing you are only calling the spawnEnemy() function when you spawn an enemy. Here’s how I would do it.

  • Create a prefab of your enemies with a ridgidbody and a move script attached to each of your enemy types. (You could also add them with code if preferred)
  • Instantiate that prefab in your spawnEnemy() switch statement.
  • You can instantiate them from a variable set in the inspector or populate your enemy array with the prefabs.

The script you attach to your enemies:

#pragma strict

var target : Transform;
var turnSpeed : float = 5.0f;
var speed : float = 100f;

private var _dir : Vector3;


function Start () {
 target = GameObject.FindWithTag("Player").transform;
}

function Update () {
	if(target){
		_dir = target.position - rigidbody.position;
		_dir.Normalize();
    	transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(_dir), turnSpeed * Time.deltaTime);
    }
}

function FixedUpdate() {
    rigidbody.AddForce(_dir * speed);
}

try this:

       go.rigidbody.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), turnSpeed*Time.deltaTime);

so its myTransform.position instead of go.rigidbody.position