Of course! This is a fantastic and common architecture for applications like virtual showrooms or architectural visualization. Here is a complete, step-by-step guide to connect a C# backend (database and API) with a Unity frontend.
Architectural Overview
We will build a two-part system:
- The Backend (Server): An ASP.NET Core Web API written in C#. This API will connect to a SQL Server database to store and retrieve data about your room products (sofas, tiles, etc.).
- The Frontend (Client): A Unity application. This will make HTTP requests to our API to get product information and then use that data to load and display the 3D models in a scene.
Here's a visual representation:
Prerequisites
Before you start, make sure you have the following installed:
- Visual Studio 2022: With the "ASP.NET and web development" workload.
- .NET 7 or later: Included with the Visual Studio workload.
- SQL Server Express: A free version of SQL Server. During installation, also install SQL Server Management Studio (SSMS).
- Unity Hub and a recent Unity Editor version (e.g., 2021.3 LTS or newer).
Part 1: The Backend (C# API and Database)
Step 1: Set Up the Database
- Open SQL Server Management Studio (SSMS) and connect to your local server instance (usually
(localdb)\mssqllocaldb or .\SQLEXPRESS).
- In the Object Explorer, right-click on Databases and select New Database.
- Name your database
UnityRoomDB and click OK.
- Right-click on your new
UnityRoomDB database and select New Query.
- Paste and execute the following SQL script to create our
Products table. This table will hold the information about your furniture.
CREATE TABLE Products (
Id INT PRIMARY KEY IDENTITY(1,1),
Name NVARCHAR(100) NOT NULL,
Category NVARCHAR(50),
Price DECIMAL(10, 2),
-- This identifier will match the 3D model filename in Unity
ModelIdentifier NVARCHAR(100) NOT NULL
);
-- Insert some sample data for testing
INSERT INTO Products (Name, Category, Price, ModelIdentifier) VALUES
('Modern Sofa', 'Sofa', 499.99, 'sofa_modern'),
('Classic Armchair', 'Chair', 129.50, 'armchair_classic'),
('Marble Floor Tile', 'Tile', 15.75, 'tile_marble'),
('Wooden Coffee Table', 'Table', 89.00, 'table_coffee');
Step 2: Create the ASP.NET Core Web API Project
- Open Visual Studio.
- Click Create a new project.
- Search for and select the ASP.NET Core Web API template. Click Next.
- Name your project
RoomProductAPI. Click Next.
- Ensure the Framework is .NET 7.0 (or newer). Leave other settings as default and click Create.
Step 3: Install Necessary NuGet Packages
We need Entity Framework Core to communicate with our SQL Server database.
- In Visual Studio, go to Tools -> NuGet Package Manager -> Package Manager Console.
- Run the following commands one by one:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Step 4: Define the Data Model
Create a C# class that represents a single record in our Products table.
- In the Solution Explorer, right-click the project and select Add -> New Folder. Name it
Models.
- Right-click the
Models folder and select Add -> Class. Name it Product.cs.
- Replace the contents of
Product.cs with the following code:
// Models/Product.cs
namespace RoomProductAPI.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string? Category { get; set; } // string? means it can be null
public decimal Price { get; set; }
public string ModelIdentifier { get; set; }
}
}
Step 5: Create the Database Context
The "DbContext" is a class that represents your session with the database, allowing you to query and save data.
- Right-click the project and select Add -> New Folder. Name it
Data.
- Right-click the
Data folder and select Add -> Class. Name it ApplicationDbContext.cs.
- Replace the contents with this code:
// Data/ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
using RoomProductAPI.Models;
namespace RoomProductAPI.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Product> Products { get; set; }
}
}
Step 6: Configure the Connection String
Tell your application how to find the database.
- Open the
appsettings.json file.
- Add a
ConnectionStrings section. Modify the Server value if your SQL Server instance has a different name.
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=UnityRoomDB;Trusted_Connection=True;"
},
"Logging": {
// ... (keep existing logging settings)
},
"AllowedHosts": "*"
}
Step 7: Register the DbContext
Configure the application to use your DbContext and the connection string.
- Open the
Program.cs file.
- Add the following
using statements at the top:
using Microsoft.EntityFrameworkCore;
using RoomProductAPI.Data;
- Add the
DbContext service before the line var app = builder.Build();:
// Add services to the container.
// This line registers the DbContext
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddControllers();
// ... (rest of the services)
Step 8: Create the API Controller with GET and POST Methods
This is the core of the API. It defines the endpoints (/api/products) that Unity will call.
- Right-click the
Controllers folder and select Add -> Controller.
- Choose API Controller - Empty. Click Add.
- Name it
ProductsController.cs.
- Replace the contents of the file with the code below.
// Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using RoomProductAPI.Data;
using RoomProductAPI.Models;
namespace RoomProductAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly ApplicationDbContext _context;
public ProductsController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/Products
// This is the GET method to fetch all products.
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
// Simply retrieve all products from the database and return them.
var products = await _context.Products.ToListAsync();
return Ok(products); // Ok() returns a 200 status code with the data.
}
// POST: api/Products
// This is the POST method to add a new product.
[HttpPost]
public async Task<ActionResult<Product>> PostProduct(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Add the new product to the context and save changes to the database.
_context.Products.Add(product);
await _context.SaveChangesAsync();
// Return a 201 Created status code, with a link to the new resource
// and the resource itself in the body.
return CreatedAtAction(nameof(GetProducts), new { id = product.Id }, product);
}
}
}
Step 9: Run and Test the API
- Press F5 or the green play button in Visual Studio to run your API.
- A browser window will open to a Swagger UI page (e.g.,
https://localhost:7123/swagger/index.html). This is a documentation and testing tool.
- Find the
/api/Products GET endpoint, expand it, click Try it out, and then Execute.
- You should see a
200 success response, and the JSON body will contain the sample data we inserted into the database!
- Important: Note the URL from the browser bar (e.g.,
https://localhost:7123). You will need this for Unity.
Your backend is now complete and running!
Part 2: The Frontend (Unity Integration)
Step 1: Set Up the Unity Project
- Open Unity Hub and create a new 3D project.
- Name it
VirtualRoom.
Step 2: Prepare 3D Models
- In your Unity Project's
Assets panel, create a new folder named Resources. The name is important and case-sensitive.
- Find or create some 3D models (e.g., in
.fbx or .glb format).
- Name your model files to exactly match the
ModelIdentifier in your database. For our example, you would need:
sofa_modern.fbx
armchair_classic.fbx
tile_marble.fbx
table_coffee.fbx
- Drag these model files into the
Assets/Resources folder.
Step 3: Create C# Scripts for API Communication
- In the
Assets panel, create a new folder called Scripts.
- Inside
Scripts, create a C# script named ProductData.cs. This script will hold the data we get from the API. It must match the structure of the JSON.
// Scripts/ProductData.cs
// This attribute is essential for JsonUtility to work.
[System.Serializable]
public class ProductData
{
public int id;
public string name;
public string category;
public float price;
public string modelIdentifier;
}
// Helper class to parse a JSON array
[System.Serializable]
public class ProductList
{
public ProductData[] products;
}
- Now, create the main script:
APIManager.cs. This will handle the web requests.
Step 4: Implement GET and POST in APIManager.cs
Open APIManager.cs and replace its content with the following:
// Scripts/APIManager.cs
using System.Collections;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
public class APIManager : MonoBehaviour
{
// IMPORTANT: Replace this with the URL from your running API
private const string API_URL = "https://localhost:7123/api/Products";
// Public method to be called by a UI button
public void GetAllProducts()
{
StartCoroutine(GetProductsCoroutine());
}
// Coroutine for the GET request
private IEnumerator GetProductsCoroutine()
{
Debug.Log("Fetching products...");
using (UnityWebRequest webRequest = UnityWebRequest.Get(API_URL))
{
// Send the request and wait for the response
yield return webRequest.SendWebRequest();
if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError("Error: " + webRequest.error);
}
else
{
Debug.Log("Received: " + webRequest.downloadHandler.text);
// Unity's JsonUtility cannot directly parse an array, so we use a wrapper class.
// We also need to add a root object name ("products") to match the wrapper.
string jsonResponse = "{\"products\":" + webRequest.downloadHandler.text + "}";
ProductList productList = JsonUtility.FromJson<ProductList>(jsonResponse);
// Now, process each product
foreach (var product in productList.products)
{
Debug.Log($"Product: {product.name}, Price: {product.price}, Model: {product.modelIdentifier}");
InstantiateProductModel(product.modelIdentifier);
}
}
}
}
// Method to instantiate a 3D model from the Resources folder
private void InstantiateProductModel(string modelIdentifier)
{
GameObject modelPrefab = Resources.Load<GameObject>(modelIdentifier);
if (modelPrefab != null)
{
// Instantiate at a random position for demonstration
Vector3 randomPos = new Vector3(Random.Range(-5, 5), 0, Random.Range(-5, 5));
Instantiate(modelPrefab, randomPos, Quaternion.identity);
Debug.Log($"Successfully instantiated {modelIdentifier}");
}
else
{
Debug.LogError($"Failed to load model from Resources: {modelIdentifier}");
}
}
// Coroutine for the POST request
public IEnumerator PostProductCoroutine(ProductData newProduct)
{
// Convert the C# object to a JSON string
string json = JsonUtility.ToJson(newProduct);
byte[] bodyRaw = Encoding.UTF8.GetBytes(json);
Debug.Log("Posting new product: " + json);
using (UnityWebRequest webRequest = new UnityWebRequest(API_URL, "POST"))
{
webRequest.uploadHandler = new UploadHandlerRaw(bodyRaw);
webRequest.downloadHandler = new DownloadHandlerBuffer();
// Crucially, set the content type header
webRequest.SetRequestHeader("Content-Type", "application/json");
yield return webRequest.SendWebRequest();
if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError("Error on POST: " + webRequest.error);
}
else
{
Debug.Log("POST successful! Response: " + webRequest.downloadHandler.text);
}
}
}
// Example of how to trigger a POST request
public void AddNewProductExample()
{
ProductData productToAdd = new ProductData
{
name = "New Floor Lamp",
category = "Lighting",
price = 75.99f,
modelIdentifier = "lamp_floor_new" // You would need a corresponding model in Resources
};
StartCoroutine(PostProductCoroutine(productToAdd));
}
}
Step 5: Create the Scene and Link Scripts
- In your Unity scene, create an empty GameObject. Right-click in the Hierarchy -> Create Empty.
- Rename it to
APIManager.
- Drag your
APIManager.cs script onto the APIManager GameObject in the Inspector.
- Now, let's create a UI button to trigger the GET request.
- Right-click in the Hierarchy -> UI -> Button - TextMeshPro. (Import TMP Essentials if prompted).
- Select the Button in the Hierarchy. In the Inspector, find the On Click () event panel.
- Click the + icon.
- Drag the
APIManager GameObject from the Hierarchy into the object slot (where it says "None (Object)").
- From the dropdown menu (where it says "No Function"), select APIManager -> GetAllProducts().
Step 6: Run the Full System!
- Make sure your SQL Server is running.
- Go back to Visual Studio and run your API project (F5). Keep it running.
- Go back to Unity.
- Press the Play button.
- Click the button you created in the Game view.
- Check the Console window in Unity. You should see the logs:
- "Fetching products..."
- The raw JSON response from your API.
- Logs for each product, like "Product: Modern Sofa, Price: 499.99, Model: sofa_modern".
- "Successfully instantiated sofa_modern".
- Look in your Scene view. You will see your 3D models instantiated at random positions!
To test the POST method, you could create another button and link its OnClick() event to the APIManager.AddNewProductExample() function. After clicking it, you can refresh the Swagger UI for your API and execute the GET request again to see the new "Floor Lamp" in your database.