How do I add a script to an item using another script?

Hello. I am trying to destroy an object once it reaches it’s final destination. I got it to where it would detect when an object was at that point, but sense I have multiple objects on this script, it destroys all of the objects with the script on it, and I only want the item at the final destination to get destroyed. Also, I can’t just use a serializefield and drag and drop the object in because I am spawning objects based off of a prefab so it just destroys all of the objects based off of that prefab. Thanks for the help!

Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyMovement : MonoBehaviour
{

[SerializeField] PathFinder pathfinder;
[SerializeField] GameObject enemyObject;

public bool isMoving;

// Use this for initialization
void Start()
{
    isMoving = true;
    PathFinder pathfinder = FindObjectOfType<PathFinder>();
    var path = pathfinder.GetPath();
    StartCoroutine(FollowPath(path));
}
void Update()
{
    CheckEnemyPosition();
}

IEnumerator FollowPath(List<Waypoint> path)
{
    foreach (Waypoint waypoint in path)
    {
        if (isMoving == true)
        {
            transform.position = new Vector3(waypoint.transform.position.x, waypoint.transform.position.z);
            yield return new WaitForSeconds(1f);
        }
        else
        {
            // Do Nothing
        }
    }
}
void CheckEnemyPosition()
{
    if (enemyObject.transform.position == pathfinder.endingWaypoint.transform.position)
    {
        
    }
}

}

Umm, why not set a collider at destination and remove everything entering it? Are destinations different for each object or change frequently?

Edit : based on your screenshot, i’d say it’s a TD game. So you can just :

  • Set up a collider for each exit
  • Set it as trigger
  • Use a trigger method to get the colliding object and delete it
    @jacobawesome8

You’re trying to destroy the one object, instead of all objects based off that prefab, right? If so, have you tried using gameObject.SetActive(false)? If not, I don’t know exactly what you’re asking.