I need help to implement Data persistence between scenes , to instantiate a Player since previous.

Hey there I need to implement a menu character selection, and choose charaters to play with.

In the CharacterSelection class, the logic for the character selection menu is implemented before the game begins. Therefore, it is important that player data and chosen character data are stored correctly in the CharacterSelection class before moving on to the next scene, where the corresponding player prefabs for the chosen characters are created.

When human players choose their characters, they must be assigned to a corresponding player so that the prefabs for the chosen characters can be created in the next scene of the game. It is important that this information is stored correctly in the CharacterSelection class so that it can be used as data for the selected characters in an object that can be accessed from the next scene. Then, in the next scene, this data can be used to create the corresponding player prefabs.

this is the CHaracter’s menu selection (not players by it self, just selecting , this scene works OK in terms of slecciont and confirm.

However I can not instantiate the “Prefab” of the selected character to the Player’s selection…
I got this script to control this logic.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
using System;
public class CharacterSelection : MonoBehaviour
{
    public Image[] characterImages;
    public Image[] selectedCharacterImages;
    public CharacterData[] characterData;
    public Sprite[] selectedCharacters;
    public int maxPlayers = 4;
    private int selectedPlayerIndex = -1;
    private int[] selectedPlayerIndices;

    int currentSelectedIndex = 0;
    private int selectedPlayers = 0;
    public bool[] playersReady;
    public GameManager gameManager;
    [SerializeField] private bool gameStarted = false;

    private Vector2 moveInput;
    public CreditsCoins creditsCoins;
    public int SelectedPlayerIndex { get => selectedPlayerIndex; set => selectedPlayerIndex = value; }
    private PlaceHoldersCharactersInstances[] placeHolderInstances;

    public static event Action OnLoadScene;
    public static event Action OnMenuSelectionCharacter;
    public static event Action OnSoundAcceptedCharacter;

    void Start()
    {

        selectedPlayerIndices = new int[maxPlayers];
        for (int i = 0; i < maxPlayers; i++)
        {
            selectedPlayerIndices[i] = -1; //
        }

        playersReady = new bool[maxPlayers];

        foreach (Image characterImage in characterImages)
        {
            characterImage.gameObject.SetActive(true);
        }

        foreach (bool playerReady in playersReady)
        {
            Debug.LogFormat("Player is ready : {0} ", playerReady); //
        }
    }

    private void StartTheGame()
    {
        if (!gameStarted && selectedPlayers > 0)
        {
            bool allReady = true;
            for (int i = 0; i < selectedPlayers; i++)
            {
                if (!playersReady[i])
                {
                    allReady = false;
                    break;
                }
            }
            if (allReady)
            {
                gameStarted = true;
                OnLoadScene?.Invoke();
            }
        }
    }


    void SelectPlayer(int playerIndex)
    {
        if (selectedPlayers < maxPlayers)
        {
            Debug.LogWarning("***SELECTING ****");
            playersReady[playerIndex] = true;
            selectedCharacterImages[selectedPlayers].sprite = selectedCharacters[playerIndex];
            selectedCharacterImages[selectedPlayers].gameObject.SetActive(true);

            selectedPlayers++;

            selectedPlayerIndices[selectedPlayers - 1] = playerIndex;

            SelectedPlayerIndex = playerIndex;
        }
        else if (SelectedPlayerIndex != playerIndex)
        {
            SelectedPlayerIndex = playerIndex;
        }
        else
        {
            selectedPlayerIndices[currentSelectedIndex] = playerIndex;
        }

        currentSelectedIndex = SelectedPlayerIndex;
        selectedCharacterImages[currentSelectedIndex].sprite = selectedCharacters[SelectedPlayerIndex];
        selectedCharacterImages[currentSelectedIndex].gameObject.SetActive(true);

        selectedCharacterImages[(currentSelectedIndex + maxPlayers - 1) % maxPlayers].gameObject.SetActive(false);

        string selectedCharacterName = characterData[SelectedPlayerIndex].characterName;

        Debug.Log("Selected character: " + selectedCharacterName);

        int readyPlayers = 0;
        for (int i = 0; i < maxPlayers; i++)
        {
            if (playersReady[i])
            {
                readyPlayers++;
            }
        }

        if (readyPlayers == maxPlayers)
        {
            OnLoadScene?.Invoke();
        }
    }


    public void OnSelectionCharacter(InputAction.CallbackContext selection)
    {
        moveInput = selection.ReadValue<Vector2>();

        if (moveInput.x > 0 && selection.performed)
        {
            SelectedPlayerIndex++;
            SelectedPlayerIndex = Mathf.Clamp(SelectedPlayerIndex, 0, maxPlayers - 1);

            selectedCharacterImages[currentSelectedIndex].gameObject.SetActive(false);
            SelectPlayer(SelectedPlayerIndex);

            OnMenuSelectionCharacter?.Invoke();
        }
        else if (moveInput.x < 0 && selection.performed && SelectedPlayerIndex != 0)
        {
            SelectedPlayerIndex--;
            SelectedPlayerIndex = Mathf.Clamp(SelectedPlayerIndex, 0, maxPlayers - 1);

            selectedCharacterImages[currentSelectedIndex].gameObject.SetActive(false);
            SelectPlayer(SelectedPlayerIndex);

            OnMenuSelectionCharacter?.Invoke();
        }

        int selectedCharacterIndex = selectedPlayerIndices[SelectedPlayerIndex];
        string selectedCharacterName = characterData[selectedCharacterIndex].characterName;

        Debug.Log("Selected character index: " + selectedCharacterIndex);
        Debug.Log("Selected character name: " + selectedCharacterName);
    }


    public void OnConfirm(InputAction.CallbackContext accept)
    {
        if (accept.performed)
        {
            Debug.Log("Accepted");

            OnSoundAcceptedCharacter?.Invoke();
            AcceptedCharacter();
        }
    }

    public void AcceptedCharacter()
    {
        int selectedCharacterIndex = selectedPlayerIndices[SelectedPlayerIndex];

        GameObject placeHoldersObject = GameObject.Find("PlaceHoldersObject");
        if (placeHoldersObject != null)
        {
            PlaceHoldersCharactersInstances placeHolders = placeHoldersObject.GetComponent<PlaceHoldersCharactersInstances>();
            if (placeHolders != null)
            {
                placeHolders.SetSelectedCharacter(selectedCharacterIndex);
            }
        }
    }

    public void CountActivePlayers()
    {
        int activePlayers = 0;
        string activePlayersText = "";

        List<PlayerReadyData> readyPlayers = creditsCoins.GetReadyPlayers();

        foreach (PlayerReadyData playerData in readyPlayers)
        {
            if (playerData.isReady)
            {
                activePlayers++;
                activePlayersText += "P" + (playerData.playerNumber + 1) + ", ";
            }
            else
            {
                activePlayersText += "(No Listo), ";
            }
        }

        Debug.LogFormat("Número of players active: {0}", activePlayers);
        Debug.LogFormat("players actives: {0}", activePlayersText);
    }
}

then I got 2 scriptable objects (one for players ready only ) and other for characterData (name,id,index,portrait,etc)

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

[CreateAssetMenu(fileName = "New Character Data", menuName = "Character Data")]
public class CharacterData : ScriptableObject
{
    public Sprite portrait;
    public string characterName;
    public int characterIndex; // Índice del personaje
   

    public enum CharacterType
    {
        Gen,
        Burn,
        Khan,
        Jack
    }

}

and the other scriptable objects when Player or players are ready …

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

[CreateAssetMenu(fileName = "PlayerReadyData", menuName = "Player Ready Data")]
public class PlayerReadyData : ScriptableObject
{
    public int playerNumber;
    public bool isReady;
    public int creditCount; // Crédito individual del jugador
    public CharacterData selectedCharacter; // Personaje seleccionado
    internal InputDevice inputDevice;  //que input usa

}

You just need to store the data in manner that is independant of scenes.

This is usually done with static classes/fields or scriptable objects to communicate data between scenes.

In your case it would be trivial to store the chosen characters in a static class, and use those values when in the actual gameplay scene.

You have several options for transferring data across scenes:

  1. Use static variables.
  2. Use DontDestoryOnLoad on Gameobject with data.
  3. Use Player Prefs.
  4. Use Serialization.
  5. Use ScriptableObjects configured for RunTime.
  6. Use Singleton class.

I prefer to use Scriptable objectes… but now I am struggle with UI input manager for multiplayer…I meant… before selecting a character I need to read the input or device related to the Player…why? because in the previous scene the first scene of the game , there is a “credit coin scene” that means is a menu where detect when/who the player is and when he/they were ready… have sense? … this credit coins menu allows the player to become “player” … example : let say the scene are reading 4 input devices, and let say one of that devices introuce credits and press “start” button via (new input system)…so whate happen? that new device which entered credit and become credit now is “PlayerN” where Player N can be Player1,Player2, etc… so if a Player1 added credit and be ready, he started the new scene (this one, in the post… character selection scene) able to choose a character!.. this scene does exist only if the previous scene detect and define a player and player UI input bofrece instantiateteh “player’s character” on the scene, I like to separate the logic of Players from Characters…

discard PlayerPrefs… serialization ? for monobehaviour? scriptable object real time? you mean just use it a config’s prefab picking? ODIN? some decoration to instantita? however yes,
prefer to use Scriptable objectes… but now I am struggle with UI input manager for multiplayer…I meant… before selecting a character I need to read the input or device related to the Player…why? because in the previous scene the first scene of the game , there is a “credit coin scene” that means is a menu where detect when/who the player is and when he/they were ready… have sense? … this credit coins menu allows the player to become “player” … example : let say the scene are reading 4 input devices, and let say one of that devices introuce credits and press “start” button via (new input system)…so whate happen? that new device which entered credit and become credit now is “PlayerN” where Player N can be Player1,Player2, etc… so if a Player1 added credit and be ready, he started the new scene (this one, in the post… character selection scene) able to choose a character!.. this scene does exist only if the previous scene detect and define a player and player UI input bofrece instantiateteh “player’s character” on the scene, I like to separate the logic of Players from Characters…

Everything that Spiney and TNR says above plus this:

ULTRA-simple static solution to a GameManager:

OR for a more-complex “lives as a MonoBehaviour or ScriptableObject” solution…

Simple Singleton (UnitySingleton):

Some super-simple Singleton examples to take and modify:

Simple Unity3D Singleton (no predefined data):

Unity3D Singleton with a Prefab (or a ScriptableObject) used for predefined data:

These are pure-code solutions, DO NOT put anything into any scene, just access it via .Instance!

The above solutions can be modified to additively load a scene instead, BUT scenes do not load until end of frame, which means your static factory cannot return the instance that will be in the to-be-loaded scene. This is a minor limitation that is simple to work around.

If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:

public void DestroyThyself()
{
   Destroy(gameObject);
   Instance = null;    // because destroy doesn't happen until end of frame
}

There are also lots of Youtube tutorials on the concepts involved in making a suitable GameManager, which obviously depends a lot on what your game might need.

OR just make a custom ScriptableObject that has the shared fields you want for the duration of many scenes, and drag references to that one ScriptableObject instance into everything that needs it. It scales up to a certain point.

And finally there’s always just a simple “static locator” pattern you can use on MonoBehaviour-derived classes, just to give global access to them during their lifecycle.

WARNING: this does NOT control their uniqueness.

WARNING: this does NOT control their lifecycle.

public static MyClass Instance { get; private set; }

void OnEnable()
{
  Instance = this;
}
void OnDisable()
{
  Instance = null;     // keep everybody honest when we're not around
}

Anyone can get at it via MyClass.Instance., but only while it exists.

Sorry but your posts are incredibly rambly and I have no idea what you’re on about or what your specific problem actually is.

Can you try and explain your problem clearly and concisely without excessive use of ellipsis?

Yes, indeed, this ^ ^ ^

For instance, when you say this:

… keep it simple. Store a reference to the selected prefab.

That’s it. You’re DONE.

Then in the next scene instantiate it.

If you more than one character, make a list of the chosen prefabs.

If you don’t know how to make UI to select such things, that’s your next task to learn.

Just know this:

These things (inventory, shop systems, character customization, dialog tree systems, crafting, etc) are fairly tricky hairy beasts, definitely deep in advanced coding territory.

Inventory code never lives “all by itself.” All inventory code is EXTREMELY tightly bound to prefabs and/or assets used to display and present and control the inventory. Problems and solutions must consider both code and assets as well as scene / prefab setup and connectivity.

Inventories / shop systems / character selectors all contain elements of:

  • a database of items that you may possibly possess / equip
  • a database of the items that you actually possess / equip currently
  • perhaps another database of your “storage” area at home base?
  • persistence of this information to storage between game runs
  • presentation of the inventory to the user (may have to scale and grow, overlay parts, clothing, etc)
  • interaction with items in the inventory or on the character or in the home base storage area
  • interaction with the world to get items in and out
  • dependence on asset definition (images, etc.) for presentation

Just the design choices of such a system can have a lot of complicating confounding issues, such as:

  • can you have multiple items? Is there a limit?
  • if there is an item limit, what is it? Total count? Weight? Size? Something else?
  • are those items shown individually or do they stack?
  • are coins / gems stacked but other stuff isn’t stacked?
  • do items have detailed data shown (durability, rarity, damage, etc.)?
  • can users combine items to make new items? How? Limits? Results? Messages of success/failure?
  • can users substantially modify items with other things like spells, gems, sockets, etc.?
  • does a worn-out item (shovel) become something else (like a stick) when the item wears out fully?
  • etc.

Your best bet is probably to write down exactly what you want feature-wise. It may be useful to get very familiar with an existing game so you have an actual example of each feature in action.

Once you have decided a baseline design, fully work through two or three different inventory tutorials on Youtube, perhaps even for the game example you have chosen above.

Breaking down a large problem such as inventory:

https://discussions.unity.com/t/826141/4

If you want to see most of the steps involved, make a “micro inventory” in your game, something whereby the player can have (or not have) a single item, and display that item in the UI, and let the user select that item and do things with it (take, drop, use, wear, eat, sell, buy, etc.).

Everything you learn doing that “micro inventory” of one item will apply when you have any larger more complex inventory, and it will give you a feel for what you are dealing with.

Breaking down large problems in general:

https://discussions.unity.com/t/908126/3

Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

How to do tutorials properly, two (2) simple steps to success:

Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That’s how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.
Fortunately this is the easiest part to get right: Be a robot. Don’t make any mistakes.
BE PERFECT IN EVERYTHING YOU DO HERE!!

If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there’s an error, you will NEVER be the first guy to find it.

Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

Finally, when you have errors, don’t post here… just go fix your errors! Here’s how:

Remember: NOBODY here memorizes error codes. That’s not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

The complete error message contains everything you need to know to fix the error yourself.

The important parts of the error message are:

  • the description of the error itself (google this; you are NEVER the first one!)
  • the file it occurred in (critical!)
  • the line number and character position (the two numbers in parentheses)
  • also possibly useful is the stack trace (all the lines of text in the lower console window)

Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly?

All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don’t have to stop your progress and fiddle around with the forum.