I'm trying to make it so that an enemy follows the player (in unity 2d). It worked before with the exact same code but after renaming the file the enemy just stands still.
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class eMovement : MonoBehaviour
{
public float moveSpeed = 3;
private Rigidbody2D rb;
public Transform target;
private Vector2 movement;
// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
target = FindObjectOfType<eMovement>().transform;
}
// Update is called once per frame
private void Update()
{
if (target)
{
Vector3 direction = (target.position - transform.position).normalized;
movement = direction;
}
}
void move(Vector2 direction)
{
rb.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime));
}
private void FixedUpdate()
{
move(movement);
}
}
There could be a problem within unity itself but I can't figure it out. Also I'm a complete noob at c# and unity so any tips are very welcome :)
In Unity, the file a MonoBehaviour
resides in must be the same exact name.
Check the console, there will be a message like:
No MonoBehaviour scripts in the file or their names do not match the file name.
To fix that error, rename your file eMovement.cs
.
This is a limitation of Unity and there is no way around it.
Note that this does not apply for POCO classes, i.e. not deriving from MonoBehaviour
.