0
votes

I'm working on a unity project in which game scene get downloaded and run at run-time. I make it work by making asset-bundle of scene and load it but problem i'm facing is scripts required by scene are not included in asset-bundle. I just got stuck here can anyone please help me that, how i can download/load required scripts or how i can include them in asset-bundle. so that i can load them at run-time also.

Sorry for bad English. Thanks.

1

1 Answers

0
votes

You can add any type of asset you want in an asset-bundle. Script (.cs file) won't be able to be included in an asset-bundle.

The way you can add all scripts/materials/.. you needs, depends on what is included in your scene, is to store them all in a folder. Then you can assign the whole folder to a AssetBundle tag as should your scene be.

Example

Your scene the client needs to download has to be in the same asset-bundle tag.

Note : if you can't store them all in the same folder, just assign their asset-bundle tag manually for each asset (or subfolder) you want to add to the bundle.

Now you can run a method to create the bundle for you, as the following :

[MenuItem("Bundles/Create all bundles")]
static void BuildAllAssetBundles()
{
    BuildPipeline.BuildAssetBundles(Path.Combine(Application.dataPath, "AssetBundleLocation"), BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
}

There is more information about How to build an asset-bundle.

Now all files required should be store in the asset-bundle file, 'Edit' except script files. Take a look at UnityEngine.AssetBundle class to load and unload bundles/assets.


Edit

What will actually work to include your script file within an asset-bundle is to write your code in a TextAsset file (.txt).

Those files will give you a string once loaded from the asset-bundle.

AssetBundle ab = AssetBundle.LoadFromFile(Path.Combine(Application.dataPath, "StreamingAssets/exampleassetbundle")); // Your asset-bundle path
TextAsset textAsset = ab.LoadAsset<TextAsset>(ab.GetAllAssetNames()[0]); // In my example I only have 1 file in the asset-bundle, the TextAsset
string flatCode = textAsset.text;

Now the thing is, you have to compile the flat string code to an actual C# class. This is called Runtime compilation.

There is many tutorials about how to do it, as this stackexchange post.

It's a bit tricky, but will do what you want.

Note : IOS and Android may not let you compile code at runtime, so depends on your target platform, you will have to investigate further.