Sure! I'll provide you with three Unity C# scripts to implement the money collection and purchase system you described. Here's an overview of the scripts:
-
MoneyManager.cs: Manages the total money across all scenes, handles saving and loading money using PlayerPrefs, and provides methods to add and spend money.
-
MoneyCollector.cs: Attached to the player character to detect collisions with objects tagged as "money" and update the money count accordingly.
-
BuyItemSystem.cs: Manages the item purchasing process, checking if the player has enough money to buy an item and enabling the item if purchased.
Additionally, I'll outline how to set up the UI elements to display the money count.
1. MoneyManager.cs
This script manages the total money, ensures it persists across scenes, and handles saving/loading using PlayerPrefs.
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class MoneyManager : MonoBehaviour
{
public static MoneyManager Instance;
[Header("UI Elements")]
public TextMeshProUGUI moneyText; // Assign in Inspector
private int totalMoney = 0;
private void Awake()
{
// Singleton pattern to ensure only one instance exists
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
LoadMoney();
}
else
{
Destroy(gameObject);
}
}
private void Start()
{
UpdateMoneyUI();
}
// Method to add money
public void AddMoney(int amount)
{
totalMoney += amount;
UpdateMoneyUI();
SaveMoney();
}
// Method to spend money
public bool SpendMoney(int amount)
{
if (totalMoney >= amount)
{
totalMoney -= amount;
UpdateMoneyUI();
SaveMoney();
return true;
}
return false;
}
// Update the UI Text
public void UpdateMoneyUI()
{
if (moneyText != null)
{
moneyText.text = "Money: $" + totalMoney.ToString();
}
}
// Save money using PlayerPrefs
private void SaveMoney()
{
PlayerPrefs.SetInt("TotalMoney", totalMoney);
PlayerPrefs.Save();
}
// Load money from PlayerPrefs
private void LoadMoney()
{
totalMoney = PlayerPrefs.GetInt("TotalMoney", 0);
}
}
Setup Instructions:
-
Create a MoneyManager GameObject:
- Create an empty GameObject in your initial scene (e.g., Main Menu) and name it
MoneyManager.
- Attach the
MoneyManager.cs script to it.
- Ensure the
MoneyManager persists across scenes by keeping it in the initial scene or managing it via persistent scenes.
-
Assign UI Text:
- Create a UI Text (using TextMeshPro for better visuals) in your scene to display the money count.
- Assign this Text to the
moneyText field in the MoneyManager component in the Inspector.
2. MoneyCollector.cs
This script should be attached to the player character. It detects collisions with objects tagged as "money" and updates the total money.
using UnityEngine;
public class MoneyCollector : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("money"))
{
// Optionally, define how much money each object gives
int moneyAmount = other.GetComponent<Money>().amount;
// Add money to MoneyManager
MoneyManager.Instance.AddMoney(moneyAmount);
// Destroy the money object
Destroy(other.gameObject);
}
}
}
Additional Setup:
-
Tagging Money Objects:
- Ensure that all money collectible objects have the tag
"money". You can create this tag by going to Tags & Layers in the Inspector.
-
Money Script on Money Objects:
- To define how much each money object is worth, create a simple script called
Money.cs and attach it to each money object.
using UnityEngine;
public class Money : MonoBehaviour
{
public int amount = 10; // Define the amount of money this object provides
}
3. BuyItemSystem.cs
This script manages purchasing items. It checks if the player has enough money and, if so, spends the money and enables the purchased item.
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class BuyItemSystem : MonoBehaviour
{
[Header("UI Elements")]
public TextMeshProUGUI itemPriceText; // Assign in Inspector
public Button buyButton; // Assign in Inspector
[Header("Item Settings")]
public int itemPrice = 50; // Set the price of the item
public GameObject itemToEnable; // Assign the item GameObject
private void Start()
{
// Update the price text
if (itemPriceText != null)
{
itemPriceText.text = "Price: $" + itemPrice.ToString();
}
// Check if item is already purchased
if (itemToEnable != null && itemToEnable.activeInHierarchy)
{
buyButton.interactable = false;
buyButton.GetComponentInChildren<TextMeshProUGUI>().text = "Purchased";
}
}
public void BuyItem()
{
if (MoneyManager.Instance.SpendMoney(itemPrice))
{
// Enable the item
if (itemToEnable != null)
{
itemToEnable.SetActive(true);
}
// Update the button
buyButton.interactable = false;
buyButton.GetComponentInChildren<TextMeshProUGUI>().text = "Purchased";
// Optionally, save the purchase status
PlayerPrefs.SetInt(itemToEnable.name + "_Purchased", 1);
PlayerPrefs.Save();
}
else
{
Debug.Log("Not enough money to buy this item.");
// Optionally, display a message to the player
}
}
private void OnEnable()
{
// Load purchase status when the script is enabled
if (itemToEnable != null)
{
bool isPurchased = PlayerPrefs.GetInt(itemToEnable.name + "_Purchased", 0) == 1;
if (isPurchased)
{
itemToEnable.SetActive(true);
if (buyButton != null)
{
buyButton.interactable = false;
buyButton.GetComponentInChildren<TextMeshProUGUI>().text = "Purchased";
}
}
}
}
}
Setup Instructions:
-
Create a Buy Button:
- In your shop or menu scene, create a UI Button for each item you want to sell.
- Attach the
BuyItemSystem script to each button.
-
Configure the BuyItemSystem Component:
- itemPriceText: Assign the TextMeshPro UI element that displays the item's price.
- buyButton: Assign the Button component itself.
- itemPrice: Set the price for the item.
- itemToEnable: Assign the GameObject you want to enable upon purchase (e.g., a weapon, power-up, etc.).
-
Hook Up the Buy Button:
- In the Button's OnClick event, add the
BuyItemSystem.BuyItem method.
-
Persisting Purchases Across Sessions:
- The script uses
PlayerPrefs to save the purchase status. Ensure that each item has a unique name to avoid conflicts.
Additional Considerations
Scene Management:
UI Setup:
- Money Display in All Scenes:
- To display the money count in multiple scenes, consider using a UI Canvas that's part of the
MoneyManager GameObject or have a dedicated UI manager that references MoneyManager.Instance.
Optimizations:
- Event System:
- For larger projects, consider implementing an event system where
MoneyManager broadcasts events when money changes, and UI elements subscribe to these events to update dynamically. This decouples your systems and improves scalability.
Error Handling:
-
Null Checks:
- Ensure that all UI elements are correctly assigned in the Inspector to avoid
NullReferenceException errors.
-
PlayerPrefs Limitations:
PlayerPrefs is suitable for small amounts of data. For more complex systems, consider using a more robust saving system.
By following these scripts and setup instructions, you'll have a functional money collection and purchase system across multiple scenes in your Unity project. Make sure to test each component thoroughly to ensure everything integrates smoothly.