Skip to content

Instantly share code, notes, and snippets.

@grofit
Created October 1, 2015 20:28
Show Gist options
  • Save grofit/8c763640d247fecb757e to your computer and use it in GitHub Desktop.
Save grofit/8c763640d247fecb757e to your computer and use it in GitHub Desktop.
uFrame MVVM View Instantiation Helpers
public static class SceneExtensions
{
public static TView InstantiatePrefabView<TView>(this IScene scene, ViewModel viewModel, string prefabName, string instanceName = null, Transform parent = null)
where TView : ViewBase, new()
{
var prefab = Resources.Load(prefabName) as GameObject;
if (prefab == null)
{ throw new Exception(string.Format("Cannot locate prefab [{0}]", prefabName)); }
var createViewCommand = new InstantiateViewCommand
{
ViewModelObject = viewModel,
Prefab = prefab,
Scene = scene
};
uFrameKernel.EventAggregator.Publish(createViewCommand);
if (createViewCommand.Result == null)
{ throw new Exception(string.Format("Could not instantiate view with prefab [{0}]", prefabName)); }
if (instanceName != null)
{ createViewCommand.Result.name = instanceName; }
if (parent != null)
{ createViewCommand.Result.transform.parent = parent; }
return createViewCommand.Result as TView;
}
public static IEnumerable<TView> InstantiateCollectionPrefabView<TView, TViewModel>(this IScene scene, ModelCollection<TViewModel> viewModels, string prefabName, string instanceNamePrefix = null, Transform parent = null)
where TView : ViewBase, new()
where TViewModel : ViewModel
{
var prefab = Resources.Load(prefabName) as GameObject;
if (prefab == null)
{ throw new Exception(string.Format("Cannot locate prefab [{0}]", prefabName)); }
var index = 0;
var viewList = new List<TView>();
foreach (var viewModel in viewModels)
{
index++;
var createViewCommand = new InstantiateViewCommand
{
ViewModelObject = viewModel,
Prefab = prefab,
Scene = scene
};
uFrameKernel.EventAggregator.Publish(createViewCommand);
if (createViewCommand.Result == null)
{ throw new Exception(string.Format("Could not instantiate view with prefab [{0}]", prefabName)); }
if (instanceNamePrefix != null)
{ createViewCommand.Result.name = string.Format("{0} - {1}", instanceNamePrefix ?? prefab.name, index); }
if(parent != null)
{ createViewCommand.Result.transform.parent = parent; }
viewList.Add(createViewCommand.Result as TView);
}
return viewList;
}
}
public class SomeSceneLoader : SceneLoader
{
[Inject]
public SomeController _someController;
public IEnumerator LoadScene(IScene scene, SomethingElse blah)
{
var myVM = _someController.CreateSomeVM();
scene.InstantiatePrefabView(myVm, "some-resource/some-view-1");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment