To achieve the desired functionality—where all itemObjects are disabled by default and only enabled if they've been purchased (persisting their state across scene restarts)—you can modify your ItemShop script as follows:
-
Ensure All itemObjects Are Managed by the Script:
- On scene start, explicitly disable all
itemObjects.
- Enable only those
itemObjects that have been purchased.
-
Persist Purchase States:
- Use
PlayerPrefs to remember which items have been purchased, ensuring they remain enabled even after restarting the scene.
-
Centralize Management (Optional but Recommended):
- For better scalability and management, especially if you have many items, consider creating a central manager that handles the initialization of all
itemObjects. This prevents multiple ItemShop instances from interfering with each other.
Below is the updated ItemShop script with detailed comments explaining each part:
using UnityEngine;
using TMPro;
public class ItemShop : MonoBehaviour
{
[Header("Item Configuration")]
public int itemID; // Unique ID for the item
public int itemPrice; // Price of the item
public GameObject itemObject; // Object that will be enabled upon purchase
public GameObject assignedObjectToDisable; // Object that will be disabled upon successful purchase
public TextMeshProUGUI feedbackText; // Optional: feedback text for the user
private MoneySaver moneySaver; // Reference to MoneySaver for total money
private void Awake()
{
// Ensure MoneySaver is available
moneySaver = FindObjectOfType<MoneySaver>();
if (moneySaver == null)
{
Debug.LogError("MoneySaver instance not found in the scene.");
}
}
private void Start()
{
// Initialize the item's active state based on purchase status
InitializeItemState();
}
/// <summary>
/// Initializes the item's active state based on whether it has been purchased.
/// </summary>
private void InitializeItemState()
{
bool isPurchased = PlayerPrefs.GetInt("PurchasedItem_" + itemID, 0) == 1;
if (isPurchased)
{
EnableItem();
HideAssignedObject();
feedbackText.text = "Item Purchased";
}
else
{
DisableItem();
ShowAssignedObject();
feedbackText.text = "Item Available";
}
}
/// <summary>
/// Attempts to purchase the item.
/// </summary>
public void AttemptPurchase()
{
int currentMoney = PlayerPrefs.GetInt("TotalMoney", 0);
// Check if the item is already purchased
if (PlayerPrefs.GetInt("PurchasedItem_" + itemID, 0) == 1)
{
feedbackText.text = "Already Purchased!";
return;
}
// Check if the player has enough money
if (currentMoney >= itemPrice)
{
// Deduct the price from total money
int updatedMoney = currentMoney - itemPrice;
PlayerPrefs.SetInt("TotalMoney", updatedMoney);
// Update MoneySaver UI
if (moneySaver != null)
{
moneySaver.UpdateTotalMoneyUI(updatedMoney);
}
// Mark the item as purchased
PlayerPrefs.SetInt("PurchasedItem_" + itemID, 1);
PlayerPrefs.Save();
// Enable the purchased item and disable the assigned object
EnableItem();
HideAssignedObject();
feedbackText.text = "Purchase Successful!";
}
else
{
feedbackText.text = "Not Enough Money!";
}
}
/// <summary>
/// Enables the itemObject.
/// </summary>
private void EnableItem()
{
if (itemObject != null)
{
itemObject.SetActive(true);
}
else
{
Debug.LogWarning($"ItemObject is not assigned for itemID {itemID}");
}
}
/// <summary>
/// Disables the itemObject.
/// </summary>
private void DisableItem()
{
if (itemObject != null)
{
itemObject.SetActive(false);
}
else
{
Debug.LogWarning($"ItemObject is not assigned for itemID {itemID}");
}
}
/// <summary>
/// Hides the assigned object (e.g., a purchase button or placeholder).
/// </summary>
private void HideAssignedObject()
{
if (assignedObjectToDisable != null)
{
assignedObjectToDisable.SetActive(false);
}
}
/// <summary>
/// Shows the assigned object.
/// </summary>
private void ShowAssignedObject()
{
if (assignedObjectToDisable != null)
{
assignedObjectToDisable.SetActive(true);
}
}
/// <summary>
/// Ensures the item's state is correctly set when the object is enabled.
/// </summary>
private void OnEnable()
{
InitializeItemState();
}
}
Explanation of Changes:
-
Initialization (InitializeItemState Method):
- This method checks if the item has been purchased using
PlayerPrefs.
- If purchased, it enables the
itemObject and disables the assignedObjectToDisable.
- If not purchased, it ensures the
itemObject is disabled and the assignedObjectToDisable is visible (e.g., showing a purchase button).
-
Purchase Attempt (AttemptPurchase Method):
- Before attempting a purchase, it checks if the item is already purchased.
- If there's enough money, it deducts the price, updates the UI, marks the item as purchased in
PlayerPrefs, and updates the item's visibility accordingly.
- Provides feedback to the user through
feedbackText.
-
Object Visibility Methods:
EnableItem and DisableItem: Manage the active state of itemObject.
HideAssignedObject and ShowAssignedObject: Manage the active state of assignedObjectToDisable.
-
OnEnable Override:
- Ensures that whenever the
ItemShop object is enabled (e.g., when the scene is reloaded), it correctly initializes the item's state based on its purchase status.
Ensuring All Items Are Managed
If you have multiple ItemShop instances (one for each item), each will independently manage its own itemObject based on its itemID. However, to ensure that all itemObjects are initially disabled (unless purchased), make sure:
Example of a Central ShopManager (Optional)
If you prefer centralized control, here's an example of how you might implement a ShopManager:
using UnityEngine;
public class ShopManager : MonoBehaviour
{
private ItemShop[] allItemShops;
private void Start()
{
allItemShops = FindObjectsOfType<ItemShop>();
foreach (ItemShop shop in allItemShops)
{
shop.InitializeItemState();
}
}
}
Usage:
- Attach the
ShopManager script to an empty GameObject in your scene.
- Ensure each
ItemShop instance has the itemID properly set and that their itemObject references are correctly assigned.
- This manager ensures that upon starting the scene, each
ItemShop initializes its state appropriately.
Final Tips:
-
PlayerPrefs Limitations:
- Remember that
PlayerPrefs is suitable for small amounts of data. For more complex data management, consider using serialization or a dedicated data management system.
-
Debugging:
- Use
Debug.Log statements to verify that items are correctly enabling/disabling based on purchases.
-
UI Feedback:
- Ensure that
feedbackText is properly assigned in the Inspector to avoid NullReferenceException errors.
By implementing these changes, all of your itemObjects will be managed by the script, ensuring that purchased items remain enabled across scene restarts, while others remain disabled until purchased.