Reputation: 11
When instantiate a prefab using the Instantiate()
method, it lags my game.
I have also tried object pooling and assetBundle.
I have loaded 4 3d-Models using prefabs.
The 3d model I am instantiating has a size of 2MB
.
Upvotes: 1
Views: 2397
Reputation: 90749
If the prefab is that huge maybe simply you device isn't capable to render it in your desired f/s.
It is also possible that the lags don't come from the model itself but from initialization (Awake
, OnEnable
) calls on components attached to that object.
If it is only slow while instantiating you should use Instantiate()
only once in Awake
or Start
and only disable/enable the objects while not needed via SetActive
(somehow what object pooling does).
In case there are more scenes involved you should use DontDestroyOnLoad
in order to carry them on to other scenes.
You could try using something like
async Task LoadModelAsync()
{
var assetBundle = await GetAssetBundle("www.my-server.com/myfile");
var prefab = await assetBundle.LoadAssetAsync<GameObject>("myasset");
GameObject.Instantiate(prefab);
assetBundle.Unload(false);
}
async Task<AssetBundle> GetAssetBundle(string url)
{
return (await new WWW(url)).assetBundle;
}
(see How to use Async-await in Unity3d - only that they are missing a ;
after (await new WWW(url)).assetBundle
)
and use it like e.g.
private void Awake()
{
InstantiateAsync();
}
async void InstantiateAsync()
{
// Example of long running code.
await LoadModelAsync();
}
(see here for even better solutions). But keep in mind the object will not be their right away but is instantiated later.
Or you could get into the new Unity Job System which seems to be even faster (claimed here)
Upvotes: 1