如何将可与数据库交互的魔方3D模型集成到HTML网站中?
How to Build a Database-Synced 3D Rubik's Cube for Your Website
Hey there! Let's walk through exactly how to create that interactive 3D Rubik's Cube where you can update colors directly from your database—whether you stick with Unity or go a more front-end focused route.
Option 1: Using Unity 3D + WebGL
This is a solid choice if you already know Unity and want to leverage its 3D editing tools.
Step 1: Build a Color-Controllable Cube in Unity
- First, model your Rubik's Cube: Break it into individual 26 small cubes (or use a pre-made asset). Assign each face of each small cube a separate material—this lets you target individual faces for color changes.
- Create a C# script (let's call it
CubeColorManager) to handle color updates. Here's a simplified example:using UnityEngine; using System; public class CubeColorManager : MonoBehaviour { // Assign each face material in the Inspector public Material[] faceMaterials; // Method to update colors from external data (like your database) public void UpdateCubeColors(string colorDataJson) { Color[] newColors = JsonUtility.FromJson<ColorArray>(colorDataJson).colors; for (int i = 0; i < faceMaterials.Length && i < newColors.Length; i++) { faceMaterials[i].color = newColors[i]; } } // Helper class for JSON parsing [Serializable] private class ColorArray { public Color[] colors; } } - Attach this script to your main Cube parent object, and drag all your face materials into the
faceMaterialsarray in the Inspector.
Step 2: Export Unity Project to WebGL
- Go to
File > Build Settings, select WebGL as the platform, then clickSwitch Platform. - Adjust build settings for web performance:
- Under
Player Settings > Resolution and Presentation, set a suitable default resolution. - Under
Player Settings > WebGL, enable compression (like Gzip) to reduce file size.
- Under
- Click
Buildand choose a folder to export your project. You'll get three key items:index.html,Build/, andTemplateData/.
Step 3: Connect to Your Database
You have two main ways to sync colors with your database:
A. Unity-side API Calls
- Use
UnityWebRequestin yourCubeColorManagerscript to fetch color data from your database's REST API. Add this method to your script:IEnumerator FetchColorsFromDatabase() { string apiUrl = "https://your-api-endpoint.com/cube-colors"; using (UnityWebRequest www = UnityWebRequest.Get(apiUrl)) { yield return www.SendWebRequest(); if (www.result == UnityWebRequest.Result.Success) { UpdateCubeColors(www.downloadHandler.text); } else { Debug.LogError("Failed to fetch colors: " + www.error); } } } - Call
StartCoroutine(FetchColorsFromDatabase())in theStart()method to load colors on initialization, or trigger it when you need to refresh.
B. Web-side JS + Unity Communication
If you prefer handling API calls in your website's JavaScript (more flexible for front-end integration):
- In your exported
index.html, add JS code to fetch color data from your database, then send it to Unity:// Wait for Unity to load document.addEventListener("DOMContentLoaded", async () => { const unityInstance = await UnityLoader.instantiate("unityContainer", "Build/CubeProject.json"); // Fetch color data from your database const response = await fetch("https://your-api-endpoint.com/cube-colors"); const colorData = await response.json(); // Send data to Unity (targets the CubeColorManager script on the Cube object) unityInstance.SendMessage("Cube", "UpdateCubeColors", JSON.stringify(colorData)); });
Step 4: Integrate with Your Website
- Upload the exported
Build/,TemplateData/, and modifiedindex.htmlto your web server. - To embed the cube into an existing page, use an
<iframe>pointing to the exportedindex.html, or copy the Unity loader code into your existing page's HTML.
Option 2: Front-End Only with Three.js (Lighter Alternative)
If you don't want to deal with Unity's WebGL export size, Three.js is a great lightweight option for building 3D content directly in the browser:
- Create a Rubik's Cube using Three.js
Meshobjects, one per small cube face. - Use JavaScript's
fetch()API to pull color data from your database. - Update each face's
material.colorproperty with the fetched values. - This approach keeps everything in your front-end code, no Unity export required, and is often faster to load for web users.
Final Tips
- Make sure your database API returns color data in a format that's easy to parse (like RGB values in JSON:
{"colors": [{"r":1,"g":0,"b":0}, ...]}). - Test the WebGL build locally first to ensure color updates work before deploying to your server.
- For performance, optimize your Unity cube model (reduce polygon count) or use Three.js's built-in primitives.
内容的提问来源于stack exchange,提问作者Nico Fossa
相关产品推荐
相关产品推荐

