So I’m having problem getting the spawned prefabs in my game to move towards, rotate towards and follow the player, I’ve looked just about everywhere for a solution, and I’m starting to get quite frustrated.
Being newer to Unity and programming, I’m aware that the solution is likely something trivial, but I would really appreciate an answer, as this is hindering my progress pretty severely.
This is my code and the scene.
Hi. I think you’re missunderstanding how you should structure/use your code.
First, the script in the screenshot is supposed to spawn enemies, not moving them. In order to move your enemies, you should create a separate script to handle that and attach it to your enemy prefab.
So, if I was you, I would remove any logic related to moving an enemy from that script, and I would put it on a new script attached to your enemy prefab.
Here’s a simple movement script that should work for your case:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
// The target that the object with this script attached will follow.
public Transform player;
// A reference to the rigidbody component.
public Rigidbody2D rigidBody;
// A variable that will increase/decrease the moving speed of the object.
public float moveSpeed;
private void Start()
{
// Find the player on the Start() method to avoid looking for it on the Update() method and gain performance.
player = GameObject.FindGameObjectWithTag("Player").transform;
}
private void FixedUpdate()
{
// This subtracts the direction the object supposed to move to. Normalizing it will make it not going too far, to keep the explanation simple.
Vector2 direction = player.position - transform.position;
direction.Normalize();
// Sets the velocity the rigidbody has to move towards the player. Applies moveSpeed aswell.
rigidBody.velocity = direction * moveSpeed;
// Rotates the enemy to look towards the player.
transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg);
}
}