Introduction
In game development, a flexible and scalable stage system can greatly enhance game balancing and content management, especially in games where difficulty, enemies, and rewards are stage-dependent. Manually adjusting each stage’s data directly in Unity can be time-consuming and error-prone. Here, I’ll show you how to leverage Google Sheets as a database to manage stage data more efficiently, and we’ll implement a complete, production-ready stage system in Unity that can dynamically load and update data directly from Google Sheets.
This guide will provide all the code necessary for you to integrate a fully functional stage system, complete with reusable components, error handling, and data structure modules. By the end, you’ll have a system that allows for real-time updates and smooth data management that can be directly used in your projects.
목차
Why Integrate Google Sheets with Unity?
Google Sheets offers several advantages as an external data management tool:
- Easily Editable: Non-developers can modify data without needing to access Unity.
- Real-Time Updates: Data changes in Google Sheets are instantly available in Unity.
- History and Version Control: Sheets provide history tracking, making it easy to revert to previous versions if needed.
Using Google Sheets as a data source, we’ll build a system that allows us to define stages, each with unique properties like enemy counts, spawn rates, health, and rewards.
System Architecture and Stage Data Structure
Before diving into the code, let’s define the structure of our stage data. We’ll use a Google Sheet with the following columns:
Stage ID | Enemy Count | Enemy Health | Spawn Rate | Reward Points |
---|---|---|---|---|
1 | 10 | 100 | 3.5 | 50 |
2 | 15 | 120 | 3.0 | 70 |
3 | 20 | 150 | 2.5 | 100 |
Each row represents a stage, and each column defines key parameters that control gameplay for that stage. Now, we’ll connect Google Sheets to Unity, set up data fetching, parsing, and a stage management system that can dynamically retrieve and apply this data.
Step-by-Step Implementation
Step 1: Set Up Google Sheets API
- Activate Google Sheets API in Google Cloud Console.
- Generate API Key and set your spreadsheet to “Anyone with the link can view.”
- Get the Sheet ID from the URL. For example, if your Sheet URL is
https://docs.google.com/spreadsheets/d/1aBcD2Ef3gH/edit#gid=0
, the Sheet ID is1aBcD2Ef3gH
.
Step 2: Configure the Unity Project and Create Data Models
Create a StageData class to define the data structure.
[System.Serializable]
public class StageData
{
public int StageId;
public int EnemyCount;
public int EnemyHealth;
public float SpawnRate;
public int RewardPoints;
public StageData(int stageId, int enemyCount, int enemyHealth, float spawnRate, int rewardPoints)
{
StageId = stageId;
EnemyCount = enemyCount;
EnemyHealth = enemyHealth;
SpawnRate = spawnRate;
RewardPoints = rewardPoints;
}
}
Step 3: Build the Google Sheets Fetcher
The following GoogleSheetsService script will handle data retrieval. It parses JSON data and maps it to our StageData
model.
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.Collections.Generic;
public class GoogleSheetsService : MonoBehaviour
{
private const string SheetsURL = "https://sheets.googleapis.com/v4/spreadsheets/YOUR_SHEET_ID/values/Sheet1?key=YOUR_API_KEY";
public IEnumerator FetchStageData(System.Action<List<StageData>> onDataLoaded)
{
UnityWebRequest request = UnityWebRequest.Get(SheetsURL);
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
List<StageData> stages = ParseStageData(request.downloadHandler.text);
onDataLoaded?.Invoke(stages);
}
else
{
Debug.LogError("Failed to fetch stage data: " + request.error);
}
}
private List<StageData> ParseStageData(string jsonData)
{
List<StageData> stageList = new List<StageData>();
// Example JSON parsing (assuming JSON format, adjust based on real format)
var rawData = JsonUtility.FromJson<RawSheetData>(jsonData);
foreach (var row in rawData.values)
{
int stageId = int.Parse(row[0]);
int enemyCount = int.Parse(row[1]);
int enemyHealth = int.Parse(row[2]);
float spawnRate = float.Parse(row[3]);
int rewardPoints = int.Parse(row[4]);
StageData stageData = new StageData(stageId, enemyCount, enemyHealth, spawnRate, rewardPoints);
stageList.Add(stageData);
}
return stageList;
}
}
[System.Serializable]
public class RawSheetData
{
public string[][] values;
}
This code provides:
- API Request Handling: Fetches data from Google Sheets via HTTP.
- JSON Parsing: Parses the fetched data into a list of
StageData
.
Step 4: Stage Manager to Apply and Handle Stage Data
We’ll create a StageManager
to load, cache, and apply stage data during gameplay. It will initialize each stage with parameters from Google Sheets, allowing dynamic stage progression.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class StageManager : MonoBehaviour
{
private List<StageData> stages;
public int currentStageIndex = 0;
public GoogleSheetsService sheetService;
private void Start()
{
StartCoroutine(sheetService.FetchStageData(OnStageDataLoaded));
}
private void OnStageDataLoaded(List<StageData> loadedStages)
{
stages = loadedStages;
InitializeStage(currentStageIndex);
}
public void InitializeStage(int stageIndex)
{
if (stageIndex < 0 || stageIndex >= stages.Count)
{
Debug.LogError("Stage index out of range.");
return;
}
StageData stage = stages[stageIndex];
Debug.Log($"Initializing Stage {stage.StageId}: " +
$"{stage.EnemyCount} enemies, " +
$"{stage.EnemyHealth} health each, " +
$"spawn every {stage.SpawnRate} seconds, " +
$"{stage.RewardPoints} points reward.");
// Add more specific stage setup logic here
}
public void NextStage()
{
if (currentStageIndex < stages.Count - 1)
{
currentStageIndex++;
InitializeStage(currentStageIndex);
}
else
{
Debug.Log("All stages complete!");
}
}
}
Explanation:
- Initialization: Loads and initializes the current stage based on data.
- Stage Transitioning: The
NextStage()
function enables dynamic progression between stages.
Step 5: Integrate and Test the System
- Attach
GoogleSheetsService
andStageManager
scripts to Unity GameObjects. - Test the system by running the game. The Stage Manager will retrieve and initialize each stage based on the data from Google Sheets.
Pros and Cons of Using Google Sheets for Stage Data
Pros:
- Simplified Data Management: Game designers and data managers can directly update Sheets without accessing Unity.
- Instant Updates: Changes in Sheets are directly reflected in Unity.
Cons:
- Network Dependency: A poor connection can lead to delays in loading data.
- API Rate Limits: Excessive API calls might lead to limitations.
Conclusion
This stage system offers a flexible, scalable, and user-friendly way to manage stage data in Unity. Integrating Google Sheets allows for real-time data management and significantly reduces repetitive tasks in Unity. By following the above steps, you should be able to seamlessly integrate this system into your project, giving your game dynamic, data-driven stages and smoother gameplay management.