Running AssetDatabase.ImportPackage on multiple packages

I’m trying to make a script which takes an array of *.unitypackage files and runs AssetDatabase.ImportPackage on each one. It seems that the script is running so fast that Unity only imports the past package in the list. Has anyone else ran into this issue and / or found a workaround?

Here’s the code snippit I’m working with:

private static void ImportPackages()
{
    //go through the entire resources directory
    string resourcePath = Application.dataPath + "/Resources";
    DirectoryInfo directory = new DirectoryInfo(resourcePath);

    //find all *.unitypackage files
    FileInfo[] unityPackageFileArray = directory.GetFiles("*.unitypackage", SearchOption.AllDirectories);

    for (int i = 0; i < unityPackageFileArray.Length; ++i)
    {
        //pared down filename starting from the Assets/ directory
        string localFilePath = unityPackageFileArray*.FullName;*

int assetIndex = localFilePath.IndexOf(“Assets\”);
if (assetIndex < 0)
{
assetIndex = 0;
}
localFilePath = localFilePath.Substring(assetIndex, localFilePath.Length - assetIndex);
localFilePath = localFilePath.Replace(‘\’, ‘/’);
Logger.Log("importing file: " + localFilePath);
//import them into the project
AssetDatabase.ImportPackage(localFilePath, true);

AssetDatabase.Refresh();
}
}
Thanks,
~Matt

I’d contacted Unity Support on this question, for a similar implementation using ImportPackage. The behavior we’d seen was the same - the import only occurs for the last package in the set. There is no workaround. Support confirmed this after we had provided examples of our attempts. ImportPackage doesn’t work when called in close succession. Subsequent instances abort prior ones leaving only the last able to complete.

I was able to get this working by instantiating an EditorWindow and using the Update function to spread out my ImportPackage calls. I had to put in a delay of about 10 frames between each call. You can’t call ImportPackage on every update. I added the file paths to a list of strings.

void Update()
{
		if (packagePaths.Count > 0)
		{
			// wait for delay. Can't import multiple packages in close succession
			if (delayFrames > 0)
			{
				delayFrames--;
				return;
			}
			
			ProcessPackage(packagePaths[0]);
			packagePaths.RemoveAt(0);
			
			delayFrames = 10;
			
			return;
		}
}

This has been fixed in Unity 4.2, but still it seems that the actual import happens after all those successive ImportPackage calls. So if for instance you have a code like this:

foreach(var path in packagePaths) {
    AssetDatabase.ImportPackage(path, false);
    someClass.prefab = (GameObject)Resources.LoadAssetAtPath(assetPath, typeof(GameObject));
}

Is not going to work, someClass.prefab will be == null since the packages will actually be imported after all of those ImportPackage calls. Probably at the end of the editor’s update frame.