104 lines
3.2 KiB
Plaintext
104 lines
3.2 KiB
Plaintext
using System;
|
|
using System.Threading.Tasks;
|
|
using UnityEngine;
|
|
using UnityEngine.Networking;
|
|
using Fusion;
|
|
|
|
public class AssetBundleNetworkDownloader : NetworkBehaviour
|
|
{
|
|
[Header("Reference")]
|
|
public GameObject map; // Where to spawn downloaded content
|
|
|
|
[Networked, OnChangedRender(nameof(OnUrlChanged))]
|
|
private NetworkString<_512> BundleUrl { get; set; }
|
|
|
|
[NonSerialized] public bool serverDownloaded = false;
|
|
|
|
private string _previousUrl = null;
|
|
|
|
public override void Spawned()
|
|
{
|
|
Debug.Log($"[AssetBundleDownloader] Spawned for {Object.InputAuthority}");
|
|
|
|
if (Object.HasInputAuthority)
|
|
{
|
|
string url = EN.instance.mapUrl;
|
|
if (!string.IsNullOrEmpty(url))
|
|
{
|
|
Debug.Log($"[AssetBundleDownloader] Setting BundleUrl to {url}");
|
|
BundleUrl = url;
|
|
}
|
|
else
|
|
{
|
|
Debug.LogWarning("[AssetBundleDownloader] Empty mapUrl in EN.instance");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// Late joiner: use already set BundleUrl
|
|
if (!string.IsNullOrEmpty(BundleUrl.ToString()))
|
|
{
|
|
_previousUrl = BundleUrl.ToString();
|
|
Debug.Log($"[AssetBundleDownloader] Late joiner loading bundle: {_previousUrl}");
|
|
_ = DownloadAndInstantiate(_previousUrl);
|
|
}
|
|
}
|
|
}
|
|
|
|
private void OnUrlChanged()
|
|
{
|
|
Debug.Log($"[AssetBundleDownloader] OnUrlChanged triggered: {BundleUrl}");
|
|
|
|
string newUrl = BundleUrl.ToString();
|
|
if (!string.IsNullOrEmpty(newUrl) && newUrl != _previousUrl)
|
|
{
|
|
_previousUrl = newUrl;
|
|
_ = DownloadAndInstantiate(newUrl);
|
|
}
|
|
}
|
|
|
|
private async Task DownloadAndInstantiate(string url)
|
|
{
|
|
serverDownloaded = false;
|
|
|
|
using (UnityWebRequest uwr = UnityWebRequestAssetBundle.GetAssetBundle(url))
|
|
{
|
|
var op = uwr.SendWebRequest();
|
|
while (!op.isDone)
|
|
await Task.Yield();
|
|
|
|
if (uwr.result != UnityWebRequest.Result.Success)
|
|
{
|
|
Debug.LogError($"[AssetBundleDownloader] Download failed: {uwr.error}");
|
|
return;
|
|
}
|
|
|
|
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwr);
|
|
if (bundle == null)
|
|
{
|
|
Debug.LogError("[AssetBundleDownloader] Failed to load AssetBundle content");
|
|
return;
|
|
}
|
|
|
|
string[] assetNames = bundle.GetAllAssetNames();
|
|
if (assetNames.Length > 0)
|
|
{
|
|
GameObject prefab = bundle.LoadAsset<GameObject>(assetNames[0]);
|
|
if (prefab != null)
|
|
{
|
|
GameObject obj = Instantiate(prefab, map ? map.transform.position : Vector3.zero, Quaternion.identity);
|
|
obj.tag = "NetworkAssetBundle";
|
|
Debug.Log("[AssetBundleDownloader] Asset instantiated.");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
Debug.LogWarning("[AssetBundleDownloader] No assets found in bundle.");
|
|
}
|
|
|
|
bundle.Unload(false); // Keep loaded assets in memory
|
|
serverDownloaded = true;
|
|
}
|
|
}
|
|
}
|