GameObject set active not working in shop system

I am trying to create a shop system in my game with the help of ChatGPT. I have made prefabs of my character skins, but the problem is that after changing scenes, the characters are not activated. Specifically, I have set all characters to be inactive by default, with only the default character being active. However, after changing scenes, no characters are active.

Here is my code:

<using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;

public class Character : MonoBehaviour
{
public static Character instance; // Static instance for easy access

public List<GameObject> characters;                      // List of character GameObjects
public List<int> characterCosts;                         // List of character costs
public List<Button> characterSelectButtons;              // List of buttons for selecting characters
public List<Button> characterPurchaseButtons;            // List of buttons for purchasing characters
public List<Image> characterSelectionIndicators;         // List of images to indicate selected characters
public TMP_Text coinsText;                               // Text for displaying coins

private int selectedCharacterIndex = 0;                  // Index of the selected character
private const int defaultCharacterIndex = 0;             // Index for the default character
private const string SelectedCharacterKey = "SelectedCharacter";
private const string PurchasedCharactersKey = "PurchasedCharacters";

private void Awake()
{
    if (instance == null)
    {
        instance = this;
        DontDestroyOnLoad(gameObject);
    }
    else
    {
        Destroy(gameObject);
    }

    // Ensure the default character is always unlocked
    PlayerPrefs.SetInt(PurchasedCharactersKey + defaultCharacterIndex, 1);
    LoadCharacterSelection();
    UpdateCharacterSelection();
    UpdateAllButtons();
    UpdateCoinsText();
}

public void PurchaseCharacter(int characterIndex)
{
    // Skip purchase logic for the default character
    if (characterIndex == defaultCharacterIndex)
    {
        Debug.Log("Default character cannot be purchased.");
        return;
    }

    int currentCoins = CoinManager.instance.GetCoins();

    if (IsCharacterPurchased(characterIndex))
    {
        Debug.Log("Character already purchased!");
        return;
    }

    if (currentCoins >= characterCosts[characterIndex])
    {
        // Reduce the player's coins by the cost of the character
        CoinManager.instance.SpendCoins(characterCosts[characterIndex]);
        
        // Unlock the purchased character
        UnlockCharacter(characterIndex);
        
        // Save the purchase and update UI elements
        SaveCharacterPurchase(characterIndex);
        UpdateAllButtons();
        UpdateCoinsText();
        
        Debug.Log("Character purchased!");
    }
    else
    {
        Debug.Log("Not enough coins!");
    }
}

public void SelectCharacter(int characterIndex)
{
    if (IsCharacterPurchased(characterIndex) || characterIndex == defaultCharacterIndex) // Allow selection if purchased or default character
    {
        selectedCharacterIndex = characterIndex;
        SaveCharacterSelection(characterIndex);
        UpdateCharacterSelection();
        UpdateSelectionIndicators();
    }
    else
    {
        Debug.Log("Character not purchased yet!");
    }
}

private void UpdateCharacterSelection()
{
    for (int i = 0; i < characters.Count; i++)
    {
        characters[i].SetActive(i == selectedCharacterIndex);
    }

    UpdateSelectionIndicators();
}

private void UpdateSelectionIndicators()
{
    for (int i = 0; i < characterSelectionIndicators.Count; i++)
    {
        characterSelectionIndicators[i].enabled = (i == selectedCharacterIndex);
    }
}

private void UpdateAllButtons()
{
    for (int i = 0; i < characters.Count; i++)
    {
        bool purchased = IsCharacterPurchased(i);
        characterSelectButtons[i].interactable = purchased;
        characterPurchaseButtons[i].gameObject.SetActive(!purchased && i != defaultCharacterIndex);
    }
}

private bool IsCharacterPurchased(int characterIndex)
{
    return PlayerPrefs.GetInt(PurchasedCharactersKey + characterIndex, 0) == 1;
}

private void SaveCharacterPurchase(int characterIndex)
{
    PlayerPrefs.SetInt(PurchasedCharactersKey + characterIndex, 1);
    PlayerPrefs.Save();
}

private void SaveCharacterSelection(int characterIndex)
{
    PlayerPrefs.SetInt(SelectedCharacterKey, characterIndex);
    PlayerPrefs.Save();
}

private void LoadCharacterSelection()
{
    selectedCharacterIndex = PlayerPrefs.GetInt(SelectedCharacterKey, defaultCharacterIndex);
}

private void UnlockCharacter(int characterIndex)
{
    // Additional logic for unlocking a character if needed
}

public void UpdateCoinsText()
{
    coinsText.text = $"Coins: {CoinManager.instance.GetCoins()}";
}

}>

Any solution???

Your script most likely simply isn’t running. Check the scene you’re going to and make sure you have this script setup and on an active game object. It seems like you’re probably calling these public functions from other scripts, which does work except for the fact that your awake function would have never run (on an inactive object), and hence your singleton instance and your data would never be initialized.

ChatGPT isn’t useful for writing code unless you already know how to code. On top of that, dumping your code here and expecting us to debug isn’t going to get you much help.

Check if the code is running at all. Check if the expected keys are written to player prefs, and being read correctly in the other scene. Etc etc. Debug until you find the problem, then look to how to solve the problem.

And learn to code the proper way: Junior Programmer Pathway - Unity Learn

2 Likes

This does not work!

Spiney already mentioned this but I like to elaborate the importance of understanding the code you enter. Because all this AI code becomes useless the moment you want to a) extend/improve it (the AI no longer has your code as reference to extend) or b) debug/fix it (you need to understand the code to be able to do so).

Ultimately, ChatGPT will give you a “working first version” that is somehow implemented to more or less do what you need to. But from then on, it’s your code and ChatGPT will be of little help.

If these “purchases” are made with real money from real people it’s all the more important that you don’t hand this over to AI.

Also consider using Unity Muse instead as it knows Unity far better than chatty.

2 Likes

Well there’s your problem! You’re not presently capable of identifying when ChatGPT gives you outright incorrect information, which is to say “Most of the time.”

Instead, try this approach: do one tiny thing at a time, just like this guy:

Imphenzia: How Did I Learn To Make Games:

ALSO… beware you are tackling one of the HARDEST things, a shop system. Here are just some of the things you will absolutely need to know 100% solid to succeed:

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

The following applies to ALL types of code listed above, but for simplicity I will call it “inventory.”

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.

If you contemplate late-delivery of content (product expansion packs, DLC, etc.), all of that has to be folded into the data source architecture from the beginning.

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
    → what it looks like lying around in the world? In a chest? On a shelf?
    → what it looks like in the inventory window itself?
    → what it looks like when worn by the player? Does it affect vision (binoculars, etc.)
    → what it looks like when used, destroyed, consumed?

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:

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:

The moment you put an inventory system into place is also a fantastic time to consider your data lifetime and persistence. Create a load/save game and put the inventory data store into that load/save data area and begin loading/saving the game state every time you run / stop the game. Doing this early in the development cycle will make things much easier later on.

Various possible inventory data structures in Unity3D:

1 Like