How to destroy a specific instantiated prefab in Unity?

78 views Asked by At

I have a scramble word game I am developing. There is a script mainly dealing with a function that instantiates a prefab. This prefab consists of a 2d square sprite of a fish and a TMP text as a child of it. The TMP text holds the unscrambled word that is loaded from a txt file when the prefab is instantiated.

There is another script that handles the movement of this prefab. So, given a velocity and speed, the fish with the attached word will move across the screen, and also destroys the instantiated prefab when it is out of bounds (i.e, the user was not able to guess it on time).

Another script handles user input.

My issue I am running into is when the user enters the return key or submits their word, I can't figure out how to "destroy" the correct instantiated prefab that the user is attempting to guess since there is usually multiple fish at once on the screen.

I've tried keeping a list of these game objects but I am not sure how to dynamically update it.

2

There are 2 answers

0
derHugo On

A bit broad of a question but here is what I would go for:

Have a list keeping track of your instances e.g. like

// Assuming this is the class you have attached to your prefab
public class Fish : MonoBehavior
{
    public static IReadOnlyList<Fish> Instances => _instances;
    private static readonly List<Fish> _instances = new();

    public string assignedWord;

    private void Awake()
    {
        _instances.Add(this);
    }

    private void OnDestroy()
    {
        _instances.Remove(this);
    }
}

This way at any point in your app you can simply access and iterate the current existing/alive instances of Fish via Fish.Instances.

Then you can get the specific instance vis the word like e.g.

//using System.Linq;

var instance = Fish.Instances.FirstOrDefault(fish => fish.assignedWord.Equals(userInput));

if(instance != null)
{
    // Valid guess => handle and destroy instance 
}
else
{
    // Invalid guess
}

In case the words a actually unique you could even rather go for a Dictionary<string, Fish> instead.

0
Voidsay On

Make a dictionary with a String key (your word) and a value of your GameObject. As long as there aren't multiple instances of the same word the code is pretty simple.

using System.Collections.Generic;
using UnityEngine;

/*Global variable*/
public Dictionary<string, GameObject> FishLookup = new Dictionary<string, GameObject>();

/*When you instantiate your fish*/
GameObject fish = Instantiate(/*your code here*/);
string word = /*your code here*/;
FishLookup.Add(word, fish);

/*When checking*/
string guess = /*your code here*/
if (FishLookup.TryGetValue(guess, out GameObject foundFish))
{
    Destroy(foundFish);
    FishLookup.Remove(guess);
}