This is my object that supposed to follow my target like a homing missile:

public Transform target;
public float movementSpeed;
public float rotataSpeed;

private Rigidbody2D rb;

private void Start()
    rb = GetComponent<Rigidbody2D>();

private void FixedUpdate()
    Vector2 direction = (Vector2)target.position - rb.position;

    float rotateAmount = Vector3.Cross(direction, -transform.up).z;

    rb.angularVelocity = -rotateAmount * rotataSpeed;
    rb.velocity = -transform.up * movementSpeed;

which works fine as the object itself but when I put it under a script that spawns this object, it work funny like it didn't really track the target when it first launch but then it did the U-turn towards my target. I want it to track my target when it first spawn. This is my spawn script:

float secondsbetweenSpawn = Mathf.Lerp(secondsBetweenSpawnMinMax.x, secondsBetweenSpawnMinMax.y, Difficulty.GetDifficultyPercentage());
if (secondsbetweenSpawn < 1.30f)
    nextSpawnTime = Time.time + secondsbetweenSpawn;
    float spawnPillSize = Random.Range(SpawnSizeMinMax.x, SpawnSizeMinMax.y);
    Vector2 spawnPosPill = new Vector2(Random.Range(-screenSize.x, screenSize.x), screenSize.y);
    GameObject pillDrop = (GameObject)Instantiate(Pill, spawnPosPill, Quaternion.identity);
    pillDrop.transform.localScale = Vector2.one * spawnPillSize;
  • 1
    \$\begingroup\$ Where do you assign a value to the target variable? \$\endgroup\$
    – DMGregory
    Jan 3 at 16:28
  • \$\begingroup\$ There must be a null reference exception because when you are Instantiating the prefab you are not assigning the value for target. \$\endgroup\$ Jan 3 at 18:11


You must log in to answer this question.

Browse other questions tagged .