Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question when i spawn an enemy through a prefab, my script for movement isnt working

Discussion in 'Scripting' started by NebojsaV, Jan 1, 2023.

  1. NebojsaV

    NebojsaV

    Joined:
    Dec 7, 2018
    Posts:
    2
    when i spawn an enemy through a prefab, my script for movement isnt working , the prefab is all set up but the new spawned enemys just go to the centre of the spawner. very new to unity so pls respond with caveman english

    this is the movement script
    public class AiEnemyMovement : MonoBehaviour
    {
    [SerializeField] private GameObject player;
    public Rigidbody2D rb2d;
    public float speed = 2;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    void FixedUpdate()
    {
    transform.position = Vector2.MoveTowards(transform.position, player.transform.position, speed * Time.deltaTime);
    }
    }
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    Hey and welcome to the forums. Please use code tags next time you post code tho :)

    When you are not sure what is going on in a problem, start by printing some information using Debug.Log!
    https://docs.unity3d.com/ScriptReference/Debug.Log.html

    You already established that some movement happens. This means the script is being executed. This also means that the speed part is not the problem. So it must be a problem with one of the two positions. Your own position (transform.position) wont ever be unavailable, so the only thing left is player.transform.position. By printing its value, you will gain new information. You will then likely find out that it's not what you think it is.
    The above roughly represents the line of thought you should have when approaching a problem.

    A prefab can only reference things within it, so unless player is part of the prefab, i'd assume it's not set.

    Also, this got nothing to do with your problem, but you dont want to put anything that is not physics into FixedUpdate. I could go into depth, but since Unity tries to make sure FixedUpdate actually gets called on fixed intervals, every bit of slowdown in there causes exponential slowdown to the actual framerate (Update) of your game. A few lines of code here or there wont make a difference, but it's a habit you shouldnt get into, which is why i mention it.
     
  3. NebojsaV

    NebojsaV

    Joined:
    Dec 7, 2018
    Posts:
    2
    thanks yoreki!
     
    Yoreki likes this.