Hello everyone,
I am working on a project in Unity with Meta VR, in which I have to load an AssetBundle (which cointains my object) into the scene at runtime.
I have a script that works and loads the object correctly, but in order to make the object appear in the scene, I have to create a new GameObject manually in the Hierarchy and then assign my scritp to it. I want to know if there is a way to avoid this step of “manually” creating the gameobject and assigning the script to it; I want to make everything from script without a lot of manual actions in unity.
Thanks in advance, this is the script that I use to load the assetbundle from a local file in my PC.
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class DownloadAssetBundleSimplifyWay : MonoBehaviour
{
// Percorso del file locale
public string filePath = "C:/Users/nicol/OneDrive/Desktop/MAGISTRALE/Comp graphics/Progetto/ProvePrefab/myfirstassetbundleprefab";
// Start is called before the first frame update
public void Start()
{
StartCoroutine(DownloadAssetBundleFromLocal());
}
private IEnumerator DownloadAssetBundleFromLocal()
{
GameObject go = null;
using (UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(filePath))
{
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogWarning("Error on the get request at " + filePath + " " + www.error);
}
else
{
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www);
go = bundle.LoadAsset<GameObject>(bundle.GetAllAssetNames()[0]) as GameObject;
bundle.Unload(false);
yield return new WaitForEndOfFrame();
}
www.Dispose();
}
InstantiateGameObjectFromAssetBundle(go);
}
private void InstantiateGameObjectFromAssetBundle(GameObject go)
{
if (go != null)
{
GameObject instanceGo = Instantiate(go) as GameObject;
instanceGo.transform.position = Vector3.zero;
}
else
{
Debug.LogWarning("Your asset bundle GameObject is null");
}
}
}
Thanks in advance.