- Home /
How to persist a List?
Hi, I would like to create a List where it should be accessible in every scenes. The List remove 1 of its item every scene. How can I retain the updated values of the List in each scenes?
Answer by YewoTheuDevs · Apr 11, 2020 at 06:56 PM
Hi @Playplyfun you could use playerprefs probably a loop however long the list is and everytime an item leaves the list change the value of an integer player pref to maybe 0 or 1 to show change then repopulate the list in next scene with a loop and if statement. Something like: string x = ""; for(i = 0; i < length of list; i++) { x = "listname" + i.ToString(); if(PlayerPrefs.GetInt(x,0) == 1) { //meaning item was removed at that index List.remove(i) } }
Answer by Quickz · Apr 11, 2020 at 09:55 PM
You have three options:
Make a static class. (Reference: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members)
Make a MonoBehaviour object that persists through scene changes (Reference: https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html).
Use a Scriptable Object (Reference: https://docs.unity3d.com/Manual/class-ScriptableObject.html).
Here's an example using a static class.
public class NumberRemover : MonoBehaviour
{
private void Start()
{
NumberData.numbers.RemoveAt(0);
}
}
public static class NumberData
{
public static List<int> numbers = new List<int>()
{
1, 2, 3, 4, 5, 6, 7, 8, 9
};
}
Your answer
Follow this Question
Related Questions
Hello, could I get some help with my inv system? 1 Answer
Respawn Method not reusable between scenes ? 0 Answers
State Machine Question 1 Answer
How do I make my joint slerp from 1 rotation to another? 1 Answer
Component goes away on play? 1 Answer