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 to enable upon purchase
public GameObject assignedObjectToDisable; // Object to disable upon purchase (e.g., Purchase Button)
public TextMeshProUGUI feedbackText; // Feedback text for the user
code
Assistant
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()
{
InitializeItemState();
}
/// <summary>
/// Initializes the item's active state based on purchase status.
/// Ensures all items are managed via script.
/// </summary>
public void InitializeItemState()
{
bool isPurchased = PlayerPrefs.GetInt("PurchasedItem_" + itemID, 0) == 1;
if (isPurchased)
{
EnableItem();
HideAssignedObject();
if (feedbackText != null)
{
feedbackText.text = "Item Purchased";
}
}
else
{
DisableItem();
ShowAssignedObject();
if (feedbackText != null)
{
feedbackText.text = "Price: $" + itemPrice;
}
}
}
/// <summary>
/// Attempts to purchase the item.
/// </summary>
public void AttemptPurchase()
{
if (moneySaver == null)
{
Debug.LogError("MoneySaver reference is missing.");
return;
}
int currentMoney = PlayerPrefs.GetInt("TotalMoney", 0);
// Check if the item is already purchased
if (PlayerPrefs.GetInt("PurchasedItem_" + itemID, 0) == 1)
{
if (feedbackText != null)
{
feedbackText.text = "Already Purchased!";
}
return;
}
// Check if the player has enough money
if (currentMoney >= itemPrice)
{
int updatedMoney = currentMoney - itemPrice;
PlayerPrefs.SetInt("TotalMoney", updatedMoney);
PlayerPrefs.Save();
// Update MoneySaver UI
moneySaver.UpdateTotalMoneyUI(updatedMoney);
// Mark the item as purchased
PlayerPrefs.SetInt("PurchasedItem_" + itemID, 1);
PlayerPrefs.Save();
// Enable the purchased item and disable the purchase button
EnableItem();
HideAssignedObject();
if (feedbackText != null)
{
feedbackText.text = "Purchase Successful!";
}
}
else
{
if (feedbackText != null)
{
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., Purchase Button).
/// </summary>
private void HideAssignedObject()
{
if (assignedObjectToDisable != null)
{
assignedObjectToDisable.SetActive(false);
}
}
/// <summary>
/// Shows the assigned object (e.g., Purchase Button).
/// </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();
}
}
Enable the itemObject variable on scene load and save the state to make it be enabled always
To ensure that the itemObject is always enabled when the scene loads and to persist this state across sessions, you'll need to adjust your ItemShop script to:
Enable the itemObject on scene load.
Save the purchase state so that itemObject remains enabled in future loads.
Here's how you can achieve this:
1. Modify the InitializeItemState Method
Ensure that the InitializeItemState method correctly sets the itemObject to active and persists this state using PlayerPrefs. Since you want the itemObject to always be enabled, you can set the purchase state to 1 (purchased) if it's not already set.
2. Update the OnEnable Method
Ensure that whenever the ItemShop component is enabled (which includes scene load), it initializes the item's state correctly.
3. (Optional) Create a Method to Force Enable the Item
If you want to programmatically enforce that an item is purchased (enabled) without going through the purchase flow, you can create an additional method.
Updated ItemShop Script
Here’s the updated ItemShop script incorporating the changes:
csharp
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 to enable upon purchase
public GameObject assignedObjectToDisable; // Object to disable upon purchase (e.g., Purchase Button)
public TextMeshProUGUI feedbackText; // 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()
{
InitializeItemState();
}
/// <summary>
/// Initializes the item's active state based on purchase status.
/// Ensures all items are managed via script.
/// </summary>
public void InitializeItemState()
{
// Check if the purchase state is already saved
bool isPurchased = PlayerPrefs.GetInt("PurchasedItem_" + itemID, 0) == 1;
if (!isPurchased)
{
// If not purchased, enable it and save the state
PlayerPrefs.SetInt("PurchasedItem_" + itemID, 1);
PlayerPrefs.Save();
isPurchased = true;
}
if (isPurchased)
{
EnableItem();
HideAssignedObject();
if (feedbackText != null)
{
feedbackText.text = "Item Purchased";
}
}
else
{
DisableItem();
ShowAssignedObject();
if (feedbackText != null)
{
feedbackText.text = "Price: $" + itemPrice;
}
}
}
/// <summary>
/// Attempts to purchase the item.
/// </summary>
public void AttemptPurchase()
{
if (moneySaver == null)
{
Debug.LogError("MoneySaver reference is missing.");
return;
}
int currentMoney = PlayerPrefs.GetInt("TotalMoney", 0);
// Check if the item is already purchased
if (PlayerPrefs.GetInt("PurchasedItem_" + itemID, 0) == 1)
{
if (feedbackText != null)
{
feedbackText.text = "Already Purchased!";
}
return;
}
// Check if the player has enough money
if (currentMoney >= itemPrice)
{
int updatedMoney = currentMoney - itemPrice;
PlayerPrefs.SetInt("TotalMoney", updatedMoney);
PlayerPrefs.Save();
// Update MoneySaver UI
moneySaver.UpdateTotalMoneyUI(updatedMoney);
// Mark the item as purchased
PlayerPrefs.SetInt("PurchasedItem_" + itemID, 1);
PlayerPrefs.Save();
// Enable the purchased item and disable the purchase button
EnableItem();
HideAssignedObject();
if (feedbackText != null)
{
feedbackText.text = "Purchase Successful!";
}
}
else
{
if (feedbackText != null)
{
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., Purchase Button).
/// </summary>
private void HideAssignedObject()
{
if (assignedObjectToDisable != null)
{
assignedObjectToDisable.SetActive(false);
}
}
/// <summary>
/// Shows the assigned object (e.g., Purchase Button).
/// </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();
}
/// <summary>
/// Forcefully enables the item and saves the purchase state.
/// Call this method if you need to enable the item outside the usual purchase flow.
/// </summary>
public void ForceEnableItem()
{
PlayerPrefs.SetInt("PurchasedItem_" + itemID, 1);
PlayerPrefs.Save();
EnableItem();
HideAssignedObject();
if (feedbackText != null)
{
feedbackText.text = "Item Enabled Permanently!";
}
}
}
Explanation of Changes
InitializeItemState Method:
Check and Set Purchase State:
First, it checks if the item is already marked as purchased in PlayerPrefs.
If not, it sets the purchase state to 1 (purchased) and saves it.
Set Item Visibility and Feedback:
If isPurchased is true, it enables the itemObject, hides the assignedObjectToDisable (e.g., Purchase Button), and updates the feedbackText to indicate that the item is purchased.
If isPurchased is false, it disables the itemObject, shows the assignedObjectToDisable, and updates the feedbackText to display the item's price.
OnEnable Method:
Calls InitializeItemState to ensure the item's state is correctly initialized whenever the component is enabled.
ForceEnableItem Method (Optional):
This method allows you to programmatically enable the item without going through the purchase process. It sets the purchase state to 1, enables the itemObject, hides the assignedObjectToDisable, and updates the feedbackText.
This can be useful for debugging or if you have special conditions under which items should be unlocked without payment.
Usage Instructions
Initial Setup:
Ensure that each ItemShop component in your scene has a unique itemID.
Assign the relevant itemObject, assignedObjectToDisable (e.g., Purchase Button), and feedbackText in the Inspector.
Scene Load Behavior:
When the scene loads, InitializeItemState is called.
If the item hasn't been marked as purchased before, it will automatically set it as purchased, enable the itemObject, hide the purchase button, and save this state.
On subsequent loads, since the purchase state is saved, the itemObject remains enabled.
Persisting Purchase State:
The purchase state is saved using PlayerPrefs. This ensures that once an item is enabled, it stays enabled across game sessions.
If you need to reset the purchase state (e.g., for testing), you can clear the relevant PlayerPrefs key or use PlayerPrefs.DeleteAll() with caution.
Optional: Forcing Item Enable:
If you want to enable an item through code (e.g., unlocking all items for a premium user), call the ForceEnableItem() method from another script.
Additional Recommendations
Security Consideration:
PlayerPrefs is not secure and can be edited by players. For critical purchase validations, consider implementing a more secure system or server-side validation.
Using MoneySaver:
Ensure that the MoneySaver script correctly manages and updates the total money, especially when items are forcefully enabled.
UI Feedback:
Customize the feedbackText to provide clear and user-friendly messages based on different scenarios (e.g., successful purchase, already purchased, insufficient funds).
By implementing these changes, your itemObject will be enabled upon scene load, and its state will persist, ensuring it remains enabled in future sessions.