Destroy instanciated object

Hello, i make simple script which instanciate the objects in the list one by one but the idea is to destroy the previous instanciated object so that only remains active one.
Any ideas?

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

public class WeaponMode : MonoBehaviour
{
    public GameObject[] mod;
    public  int currentActive = 0;


    void Update()
    {
        if (Input.GetKeyDown(KeyCode.D))
        {
             Instantiate(PreviewMod(), transform.position, Quaternion.identity);
        }
    }


    public GameObject PreviewMod()
    {
       
        if (currentActive == 0) currentActive = mod.Length - 1;
        else currentActive--;
        for (int i = 0; i < mod.Length; i++)
        {
            if (i == currentActive)
            return mod[i];
        }
        return null;
    }

}

.

Sure — Instantiate returns a reference to the newly instantiated object. You just need to keep this in a field on your class, and then call Destroy on it before you instantiate a new one.

2 Likes

This probably works. It is basically what other Joe said.

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

public class WeaponMode : MonoBehaviour
{
    public GameObject[] mod;
    public  int currentActive = 0;
    private GameObject lastSpawnedObject = null;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.D))
        {
            if (lastSpawnedObject != null)
            {
                Destroy(lastSpawnedObject);
            }
            lastSpawnedObject = Instantiate(PreviewMod(), transform.position, Quaternion.identity);
        }
    }


    public GameObject PreviewMod()
    {
     
        if (currentActive == 0) currentActive = mod.Length - 1;
        else currentActive--;
        for (int i = 0; i < mod.Length; i++)
        {
            if (i == currentActive)
            return mod[i];
        }
        return null;
    }

}