Home > OS >  Delete element from a list while changing scene in Unity
Delete element from a list while changing scene in Unity

Time:06-01

I have a list with 7 elements in Unity. At the beginning of the scene, one element is getting activated for 3 seconds and then deactivated. Then the user has to search for this element in the scene and once he/she finds it to press the trigger button to advance to the next scene. What I want to achieve is to remove the elements that have already been activated, so the user do not see them in the next scenes. So, if in the first scene the element 6 was activated, then in the second scene any element can be activated but not 6. And so on and so forth for the next scenes. Until now, I have the script below:

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

public class TrialHandler : MonoBehaviour
{
    public static TrialHandler instance;
    public List<GameObject> objectsList = new List<GameObject>();
    private int currentObject;
    private float timer;
    [HideInInspector] public static int trialNum = 0;

    private void Awake()
    {
        objectsList.RemoveAll(item => item = null);
        instance = this;
        DontDestroyOnLoad(this.gameObject);
    }
    void Start()
    {
        currentObject = Random.Range(0, objectsList.Count);
        objectsList[currentObject].SetActive(true);
        trialNum  = 1;
    }

    // Update is called once per frame
    void Update()
    {
        timer  = Time.deltaTime;
        if (timer >= 3.0f)
        {
            objectsList[currentObject].SetActive(false);
        }
    }
}

It works fine for the most part except that it repeats elements that the user has already seen as he/she goes over the scenes. I have put this code objectsList.RemoveAll(item => item = null); but it doesn't seem to get rid off the elements that have been deactivated once a new scene is loaded.

Any ideas? Thanks in advance.

CodePudding user response:

From what I understand you need to remove the gameobject from the list when you go to the next scene.i.e. when you click(trigger button-onclick listener) the next scene.No need to remove the all the items.Since you are using DontDestroyOnLoad you could use RemoveAt(index).

int index = TrialHandler.instance.objectsList
TrialHandler.instance.objectsList.RemoveAt(currentObject) //Currentobject is the index.

CodePudding user response:

Since your list contains GameObjects you can just compare like for like. In TrialHandler add a new void:

public void RemoveObject(Gameobject g)
{
   objectsList.Remove(g);
}

As you're using a singleton pattern you can access TrialHandler via a script on the clicked objects. Use the IPointerClickHandler interface to detect the click (or alternatively use raycasting):

public class ClickedObject: IPointerClickHandler
{
    public void OnPointerClick(PointerEventData pointerEventData)
    {
        TrialHandler.instance.RemoveObject(gameObject);
    }
}
  • Related