public static GameObject InstantiatePrefab(string name) { Object prefab = AssetDatabase.LoadAssetAtPath("Assets/" + root + "Prefabs/" + name, typeof(GameObject)); return((GameObject)PrefabUtility.InstantiatePrefab(prefab)); }
void OnWizardCreate() { if (!character) { UnityEditor.EditorUtility.DisplayDialog("Error", "Character not assiged.", "OK"); return; } if (!character.activeSelf) { character.SetActive(true); } PrefabType ptype = PrefabUtility.GetPrefabType(character); bool needs2create = ptype == PrefabType.ModelPrefab; if (needs2create) { character = Instantiate(character); Undo.RegisterCreatedObjectUndo(character, "Create Player"); } Animator anim = _createAnimator(); if (!anim) { Debug.LogError("Error creating character. Could not add animator component." + " < " + this.ToString() + ">"); return; } EditorUtils.CreateGameControllerObject(CharacterType != CharacterTypes.Default); _createCapsule(); _createRigidbody(); _createAudiosource(); _createTPCharacter(); _createRagdollManager(); UnityEngine.UI.Text triggerUI = _createUI(); _createTriggerManager(triggerUI); _createIKHelper(); BaseCamera camera = null; camera = _createCamera(); _createPlayerScript(camera); _createLegsIK(); if (CharacterType != CharacterTypes.TopDown) { _createSlopeScript(); // dont need for top down system because its traversing on navmesh } _createAudio(); _createPlayerControl(); _createStats(); _createEquipmentScript(); _createItemPicker(); character.tag = "Player"; character.name = characterName; character.layer = LayerMask.NameToLayer("PlayerLayer"); Undo.SetCurrentGroupName("Create Player"); if (!camera) { Debug.Log("camera is null."); } else { Debug.Log("camera " + camera.name + " parent: " + (camera.transform.parent == null ? "NULL" : camera.transform.parent.name)); } if (OnCreate != null) { OnCreate(); } }
public static uint BuildAssetBundle(Object asset, string path, BuildTarget buildTarget, KResourceQuality quality) { if (asset == null || string.IsNullOrEmpty(path)) { BuildError("BuildAssetBundle: {0}", path); return(0); } var assetNameWithoutDir = asset.name.Replace("/", "").Replace("\\", ""); // 防止多重目录... string tmpPrefabPath = string.Format("Assets/{0}.prefab", assetNameWithoutDir); PrefabType prefabType = PrefabUtility.GetPrefabType(asset); string relativePath = path; path = MakeSureExportPath(path, buildTarget, quality); var assetPath = AssetDatabase.GetAssetPath(asset); CheckAndLogDependencies(assetPath); uint crc = 0; if (asset is Texture2D) { if (!string.IsNullOrEmpty(assetPath)) // Assets内的纹理 // Texutre不复制拷贝一份 { _DoBuild(out crc, asset, null, path, relativePath, buildTarget); } else { // 内存的图片~临时创建Asset, 纯正的图片, 使用Sprite吧 var memoryTexture = asset as Texture2D; var memTexName = memoryTexture.name; var tmpTexPath = string.Format("Assets/Tex_{0}_{1}.png", memoryTexture.name, Path.GetRandomFileName()); Log.Warning("【BuildAssetBundle】Build一个非Asset 的Texture: {0}", memoryTexture.name); File.WriteAllBytes(tmpTexPath, memoryTexture.EncodeToPNG()); AssetDatabase.ImportAsset(tmpTexPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); var tmpTex = (Texture2D)AssetDatabase.LoadAssetAtPath(tmpTexPath, typeof(Texture2D)); asset = tmpTex; try { asset.name = memTexName; _DoBuild(out crc, asset, null, path, relativePath, buildTarget); } catch (Exception e) { Log.LogException(e); } File.Delete(tmpTexPath); if (File.Exists(tmpTexPath + ".meta")) { File.Delete(tmpTexPath + ".meta"); } } } else if ((prefabType == PrefabType.None && assetPath == string.Empty) || (prefabType == PrefabType.ModelPrefabInstance)) // 非prefab对象 { Object tmpInsObj = (GameObject)GameObject.Instantiate(asset); // 拷出来创建Prefab Object tmpPrefab = PrefabUtility.CreatePrefab(tmpPrefabPath, (GameObject)tmpInsObj, ReplacePrefabOptions.Default); CheckAndLogDependencies(tmpPrefabPath); asset = tmpPrefab; _DoBuild(out crc, asset, null, path, relativePath, buildTarget); GameObject.DestroyImmediate(tmpInsObj); AssetDatabase.DeleteAsset(tmpPrefabPath); } else if (prefabType == PrefabType.PrefabInstance) { var prefabParent = PrefabUtility.GetPrefabParent(asset); _DoBuild(out crc, prefabParent, null, path, relativePath, buildTarget); } else { //Log.Error("[Wrong asse Type] {0}", asset.GetType()); _DoBuild(out crc, asset, null, path, relativePath, buildTarget); } return(crc); }
private void EditorGrabDetails(string folderName, Terrain terrainTarget, int layer) { if (terrainTarget == null) { MTLog.LogError("no active terrain"); return; } TerrainData data = terrainTarget.terrainData; int detailLayerCnt = data.detailPrototypes.Length; int dataLen = data.detailResolution * data.detailResolution; string[] savedAssets = new string[detailLayerCnt]; Bounds bound = data.bounds; float pixelSize = bound.size.x / data.detailResolution; for (int i = 0; i < detailLayerCnt; ++i) { MemoryStream ms = new MemoryStream(); int totalCnt = 0; MTFileUtils.WriteInt(ms, totalCnt); DetailPrototype proto = data.detailPrototypes[i]; //prototype info //raw data int[,] dlayer = data.GetDetailLayer(0, 0, data.detailResolution, data.detailResolution, i); for (int u = 0; u < data.detailResolution; ++u) { for (int v = 0; v < data.detailResolution; ++v) { ushort pixelDen = (ushort)dlayer[v, u]; //gen data inside if (pixelDen <= 0) { continue; } //data count long countOffset = ms.Position; MTFileUtils.WriteUShort(ms, pixelDen); int subGridSize = Mathf.CeilToInt(Mathf.Sqrt(pixelDen)); float start_x = bound.min.x + u * pixelSize; float start_z = bound.min.z + v * pixelSize; ushort spawnedCount = SpawnOnePixel(proto, layer, start_x, start_z, pixelSize, subGridSize, pixelDen, bound.max.y, ms); if (countOffset != pixelDen) { long posCache = ms.Position; ms.Position = countOffset; MTFileUtils.WriteUShort(ms, spawnedCount); ms.Position = posCache; } totalCnt += spawnedCount; EditorUtility.DisplayProgressBar("bake details", "processing", (float)(u * data.detailResolution + v) / (data.detailResolution * data.detailResolution)); } } ms.Position = 0; MTFileUtils.WriteInt(ms, totalCnt); savedAssets[i] = ExportDensity2Bytes(folderName, i, ms); ms.Close(); } EditorUtility.ClearProgressBar(); AssetDatabase.Refresh(); //add componet and parameter GameObject prefabObj = new GameObject("detail_layers"); prefabObj.transform.position = terrainTarget.transform.position; MTDetailBatchRenderer dr = prefabObj.AddComponent <MTDetailBatchRenderer>(); dr.layers = new MTDetailBatchRenderer.ProtoLayerInfo[detailLayerCnt]; for (int i = 0; i < detailLayerCnt; ++i) { DetailPrototype proto = data.detailPrototypes[i]; if (savedAssets[i] == null || proto.prototype == null) { continue; } MeshFilter mf = proto.prototype.GetComponent <MeshFilter>(); if (mf == null) { continue; } MeshRenderer mr = proto.prototype.GetComponent <MeshRenderer>(); if (mr == null) { continue; } TextAsset asset = AssetDatabase.LoadAssetAtPath <TextAsset>(savedAssets[i]); dr.layers[i] = new MTDetailBatchRenderer.ProtoLayerInfo(); dr.layers[i].detailData = asset; dr.layers[i].mesh = mf.sharedMesh; dr.layers[i].mat = mr.sharedMaterial; } dr.bnds = bound; //dr.detailShader = AssetDatabase.LoadAssetAtPath<ComputeShader>("Assets/MightyTerrainMesh/Shaders/TerrainDetailMask"); dr.detailDistance = Terrain.activeTerrain.detailObjectDistance; dr.detailDensity = Terrain.activeTerrain.detailObjectDensity; dr.detailResolution = data.detailResolution; dr.detailResolutionPerPatch = data.detailResolutionPerPatch; string prefabPath = Path.Combine(folderName, "detail_layers.prefab"); PrefabUtility.SaveAsPrefabAsset(prefabObj, prefabPath); DestroyImmediate(prefabObj); AssetDatabase.Refresh(); }
protected void finishRecording(ProgressBar progress) { progress.Begin(5, "Saving Recording", "", () => { if (!_isRecording) { return; } _isRecording = false; //Turn on auto-pushing for all auto-proxy components foreach (var autoProxy in GetComponentsInChildren <AutoValueProxy>()) { autoProxy.autoPushingEnabled = true; } progress.Begin(1, "", "Reverting Scene State", () => { foreach (var pair in _initialTransformData) { pair.Key.localPosition = pair.Value.localPosition; pair.Key.localRotation = pair.Value.localRotation; pair.Key.localScale = pair.Value.localScale; pair.Key.gameObject.SetActive(pair.Value.enabled); } foreach (var pair in _initialActivityData) { EditorUtility.SetObjectEnabled(pair.Key, pair.Value); } }); progress.Begin(1, "", "Patching Materials: ", () => { GetComponentsInChildren(true, _recorders); foreach (var recorder in _recorders) { DestroyImmediate(recorder); } //Patch up renderer references to materials var allMaterials = Resources.FindObjectsOfTypeAll <Material>(). Query(). Where(AssetDatabase.IsMainAsset). ToList(); var renderers = GetComponentsInChildren <Renderer>(includeInactive: true); progress.Begin(renderers.Length, "", "", () => { foreach (var renderer in renderers) { progress.Step(renderer.name); var materials = renderer.sharedMaterials; for (int i = 0; i < materials.Length; i++) { var material = materials[i]; if (!AssetDatabase.IsMainAsset(material)) { var matchingMaterial = allMaterials.Query().FirstOrDefault(m => material.name.Contains(m.name) && material.shader == m.shader); if (matchingMaterial != null) { materials[i] = matchingMaterial; } } } renderer.sharedMaterials = materials; } }); }); progress.Begin(_behaviourActivity.Count, "", "Converting Activity Data: ", () => { foreach (var pair in _behaviourActivity) { var targetBehaviour = pair.Key; var activityData = pair.Value; progress.Step(targetBehaviour.name); string path = AnimationUtility.CalculateTransformPath(targetBehaviour.transform, transform); Type type = targetBehaviour.GetType(); string propertyName = "m_Enabled"; AnimationCurve curve = new AnimationCurve(); foreach (var dataPoint in activityData) { int index = curve.AddKey(dataPoint.time, dataPoint.enabled ? 1 : 0); AnimationUtility.SetKeyLeftTangentMode(curve, index, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyRightTangentMode(curve, index, AnimationUtility.TangentMode.Constant); } if (curve.IsConstant()) { continue; } var binding = EditorCurveBinding.FloatCurve(path, type, propertyName); if (_curves.ContainsKey(binding)) { Debug.LogError("Binding already existed?"); Debug.LogError(binding.path + " : " + binding.propertyName); continue; } _curves.Add(binding, curve); } }); progress.Begin(_transformData.Count, "", "Converting Transform Data: ", () => { foreach (var pair in _transformData) { var targetTransform = pair.Key; var targetData = pair.Value; progress.Step(targetTransform.name); string path = AnimationUtility.CalculateTransformPath(targetTransform, transform); bool isActivityConstant = true; bool isPositionConstant = true; bool isRotationConstant = true; bool isScaleConstant = true; { bool startEnabled = targetData[0].enabled; Vector3 startPosition = targetData[0].localPosition; Quaternion startRotation = targetData[0].localRotation; Vector3 startScale = targetData[0].localScale; for (int i = 1; i < targetData.Count; i++) { isActivityConstant &= targetData[i].enabled == startEnabled; isPositionConstant &= targetData[i].localPosition == startPosition; isRotationConstant &= targetData[i].localRotation == startRotation; isScaleConstant &= targetData[i].localScale == startScale; } } for (int i = 0; i < TransformData.CURVE_COUNT; i++) { string propertyName = TransformData.GetName(i); Type type = typeof(Transform); AnimationCurve curve = new AnimationCurve(); var dataType = TransformData.GetDataType(i); switch (dataType) { case TransformDataType.Position: if (isPositionConstant) { continue; } break; case TransformDataType.Rotation: if (isRotationConstant) { continue; } break; case TransformDataType.Scale: if (isScaleConstant) { continue; } break; case TransformDataType.Activity: if (isActivityConstant) { continue; } type = typeof(GameObject); break; } for (int j = 0; j < targetData.Count; j++) { int index = curve.AddKey(targetData[j].time, targetData[j].GetFloat(i)); if (dataType == TransformDataType.Activity) { AnimationUtility.SetKeyLeftTangentMode(curve, index, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyRightTangentMode(curve, index, AnimationUtility.TangentMode.Constant); } } var binding = EditorCurveBinding.FloatCurve(path, type, propertyName); if (_curves.ContainsKey(binding)) { Debug.LogError("Duplicate object was created??"); Debug.LogError("Named " + targetTransform.name + " : " + binding.path + " : " + binding.propertyName); } else { _curves.Add(binding, curve); } } } }); progress.Begin(_curves.Count, "", "Compressing Data: ", () => { foreach (var pair in _curves) { EditorCurveBinding binding = pair.Key; AnimationCurve curve = pair.Value; progress.Step(binding.propertyName); GameObject animationGameObject; { var animatedObj = AnimationUtility.GetAnimatedObject(gameObject, binding); if (animatedObj is GameObject) { animationGameObject = animatedObj as GameObject; } else { animationGameObject = (animatedObj as Component).gameObject; } } //But if the curve is constant, just get rid of it! if (curve.IsConstant()) { //Check to make sure there are no other matching curves that are //non constant. If X and Y are constant but Z is not, we need to //keep them all :( if (_curves.Query().Where(p => p.Key.path == binding.path && p.Key.type == binding.type && p.Key.propertyName.TrimEnd(2) == binding.propertyName.TrimEnd(2)). All(k => k.Value.IsConstant())) { continue; } } //First do a lossless compression curve = AnimationCurveUtil.Compress(curve, Mathf.Epsilon); Transform targetTransform = null; var targetObj = AnimationUtility.GetAnimatedObject(gameObject, binding); if (targetObj is GameObject) { targetTransform = (targetObj as GameObject).transform; } else if (targetObj is Component) { targetTransform = (targetObj as Component).transform; } else { Debug.LogError("Target obj was of type " + targetObj.GetType().Name); } var dataRecorder = targetTransform.GetComponent <RecordedData>(); if (dataRecorder == null) { dataRecorder = targetTransform.gameObject.AddComponent <RecordedData>(); } dataRecorder.data.Add(new RecordedData.EditorCurveBindingData() { path = binding.path, propertyName = binding.propertyName, typeName = binding.type.Name, curve = curve }); } }); progress.Step("Finalizing Prefab..."); var postProcessComponent = gameObject.AddComponent <HierarchyPostProcess>(); GameObject myGameObject = gameObject; DestroyImmediate(this); string targetFolderPath = targetFolder.Path; if (targetFolderPath == null) { if (myGameObject.scene.IsValid() && !string.IsNullOrEmpty(myGameObject.scene.path)) { string sceneFolder = Path.GetDirectoryName(myGameObject.scene.path); targetFolderPath = Path.Combine(sceneFolder, "Recordings"); } else { targetFolderPath = Path.Combine("Assets", "Recordings"); } } int folderSuffix = 1; string finalSubFolder; do { finalSubFolder = Path.Combine(targetFolderPath, recordingName + " " + folderSuffix.ToString().PadLeft(2, '0')); folderSuffix++; } while (Directory.Exists(finalSubFolder)); Directory.CreateDirectory(finalSubFolder); AssetDatabase.Refresh(); postProcessComponent.recordingName = recordingName; postProcessComponent.assetFolder.Path = finalSubFolder; postProcessComponent.leapData = _leapData; string prefabPath = Path.Combine(finalSubFolder, recordingName + " Raw.prefab"); PrefabUtility.CreatePrefab(prefabPath.Replace('\\', '/'), myGameObject); AssetDatabase.Refresh(); EditorApplication.isPlaying = false; }); }
/// <summary> /// Search the entire project for required assets. /// </summary> void Search() { mSearched = true; if (mExtensions != null) { string[] paths = AssetDatabase.GetAllAssetPaths(); bool isComponent = mType.IsSubclassOf(typeof(Component)); BetterList <Object> list = new BetterList <Object>(); for (int i = 0; i < mObjects.Length; ++i) { if (mObjects[i] != null) { list.Add(mObjects[i]); } } for (int i = 0; i < paths.Length; ++i) { string path = paths[i]; bool valid = false; for (int b = 0; b < mExtensions.Length; ++b) { if (path.EndsWith(mExtensions[b], System.StringComparison.OrdinalIgnoreCase)) { valid = true; break; } } if (!valid) { continue; } EditorUtility.DisplayProgressBar("Loading", "Searching assets, please wait...", (float)i / paths.Length); Object obj = AssetDatabase.LoadMainAssetAtPath(path); if (obj == null || list.Contains(obj)) { continue; } if (!isComponent) { System.Type t = obj.GetType(); if (t == mType || t.IsSubclassOf(mType) && !list.Contains(obj)) { list.Add(obj); } } else if (PrefabUtility.GetPrefabType(obj) == PrefabType.Prefab) { Object t = (obj as GameObject).GetComponent(mType); if (t != null && !list.Contains(t)) { list.Add(t); } } } list.Sort(delegate(Object a, Object b) { return(a.name.CompareTo(b.name)); }); mObjects = list.ToArray(); } EditorUtility.ClearProgressBar(); }
private void OnSceneGUI() { var e = Event.current; switch (e.type) { case EventType.MouseDown: ClearSelection(); break; case EventType.KeyDown: if (Event.current.keyCode == KeyCode.A) { _mode = PaintMode.Additive; } else if (Event.current.keyCode == KeyCode.S) { _mode = PaintMode.Subtract; } break; case EventType.KeyUp: if (Event.current.keyCode == KeyCode.Escape) { ClearSelection(); return; } if (Event.current.keyCode == KeyCode.A || Event.current.keyCode == KeyCode.S) { _mode = PaintMode.None; } if (Event.current.keyCode == KeyCode.Space) { if (MapEditor.ActiveSet != null) { var activeList = MapEditor.TileSets[MapEditor.ActiveSet]; if (activeList.Count == 0) { return; } foreach (var selectedTile in _selectedObjects) { var choosen = Random.Range(0, activeList.Count - 1); var targetTile = activeList[choosen]; var newTile = PrefabUtility.InstantiatePrefab(targetTile) as Tile; newTile.transform.position = selectedTile.transform.position; newTile.transform.SetParent(selectedTile.transform.parent); newTile.X = selectedTile.X; newTile.Y = selectedTile.Y; MapEditor.ReplaceTile(selectedTile, newTile); DestroyImmediate(selectedTile.gameObject); } } else { Debug.LogWarning("No matching tile selected"); } ClearSelection(); } break; } }
public SceneObjectsProvider(string providerId, string displayName = null) : base(providerId, displayName) { priority = 50; filterId = "h:"; subCategories = new List <NameId> { new NameId("fuzzy", "fuzzy"), }; isEnabledForContextualSearch = () => QuickSearchTool.IsFocusedWindowTypeName("SceneView") || QuickSearchTool.IsFocusedWindowTypeName("SceneHierarchyWindow"); EditorApplication.hierarchyChanged += () => m_HierarchyChanged = true; onEnable = () => { if (m_HierarchyChanged) { componentsById.Clear(); indexer = null; gods = null; m_GodBuilderEnumerator = null; m_HierarchyChanged = false; } }; onDisable = () => {}; fetchItems = (context, items, provider) => FetchItems(context, provider); fetchLabel = (item, context) => { if (item.label != null) { return(item.label); } var go = ObjectFromItem(item); if (!go) { return(item.id); } var transformPath = GetTransformPath(go.transform); var components = go.GetComponents <Component>(); if (components.Length > 2 && components[1] && components[components.Length - 1]) { item.label = $"{transformPath} ({components[1].GetType().Name}..{components[components.Length-1].GetType().Name})"; } else if (components.Length > 1 && components[1]) { item.label = $"{transformPath} ({components[1].GetType().Name})"; } else { item.label = $"{transformPath} ({item.id})"; } long score = 1; List <int> matches = new List <int>(); var sq = CleanString(context.searchQuery); if (FuzzySearch.FuzzyMatch(sq, CleanString(item.label), ref score, matches)) { item.label = RichTextFormatter.FormatSuggestionTitle(item.label, matches); } return(item.label); }; fetchDescription = (item, context) => { #if QUICKSEARCH_DEBUG item.description = gods[(int)item.data].name + " * " + item.score; #else var go = ObjectFromItem(item); item.description = GetHierarchyPath(go); #endif return(item.description); }; fetchThumbnail = (item, context) => { var obj = ObjectFromItem(item); if (obj == null) { return(null); } item.thumbnail = PrefabUtility.GetIconForGameObject(obj); if (item.thumbnail) { return(item.thumbnail); } return(EditorGUIUtility.ObjectContent(obj, obj.GetType()).image as Texture2D); }; fetchPreview = (item, context, size, options) => { var obj = ObjectFromItem(item); if (obj == null) { return(item.thumbnail); } var assetPath = GetHierarchyAssetPath(obj, true); if (String.IsNullOrEmpty(assetPath)) { return(item.thumbnail); } return(AssetPreview.GetAssetPreview(obj) ?? Utils.GetAssetPreviewFromPath(assetPath)); }; startDrag = (item, context) => { var obj = ObjectFromItem(item); if (obj != null) { DragAndDrop.PrepareStartDrag(); DragAndDrop.objectReferences = new[] { obj }; DragAndDrop.StartDrag("Drag scene object"); } }; trackSelection = (item, context) => PingItem(item); }
void PutEntities(HexXY p) { if (!isInEntitySetMode) { return; } //Creating/selecting/rotating if (Input.GetMouseButtonDown(0)) { if (Input.GetKey(KeyCode.LeftControl)) { var ent = Level.S.GetEntities(p).FirstOrDefault(); if (ent != null && ent is IRotatable && !(ent is Rune)) { var op = new Undos.RotateEntity(ent, p); op.Rotate(); undos.Push(op); redos.Clear(); } } else { var existingEntity = Level.S.GetEntities(p).FirstOrDefault(); if (existingEntity != null) { Selection.activeGameObject = entities[existingEntity.graphicsHandle]; draggedEntity = existingEntity; draggedEntityOrigPos = draggedEntityCurrPos = existingEntity.pos; } else //TODO: make possible stacking entities with Alt or something? { var prefab = Selection.activeGameObject; if (prefab == null || PrefabUtility.GetPrefabType(prefab) == PrefabType.None) { return; } var gr = prefab.GetComponent <EntityGraphics>(); if (gr == null) { return; } var ent = gr.CreateEntity(); var op = new Undos.AddEntity(ent, p); op.Add(); undos.Push(op); redos.Clear(); } } } //Deleting if (Input.GetKeyDown(KeyCode.Space)) { var ent = Level.S.GetEntities(p).FirstOrDefault(); if (ent != null) { var op = new Undos.RemoveEntity(ent, p); op.Remove(); undos.Push(op); redos.Clear(); } } //Dragging if (draggedEntity != null) { if (Input.GetMouseButton(0)) { //Drag if (p != draggedEntityCurrPos) { var op = new Undos.MoveEntity(draggedEntity, draggedEntityCurrPos, p); op.Move(); draggedEntityCurrPos = p; } } else { //Release if (draggedEntityCurrPos != draggedEntityOrigPos) { var op = new Undos.MoveEntity(draggedEntity, draggedEntityOrigPos, draggedEntityCurrPos); op.Move(); redos.Clear(); undos.Push(op); } draggedEntity = null; } } }
/// <summary> /// Sets up the current scene to be a compatible Liminal Experience App. /// </summary> public static void SetupAppScene() { var scene = SceneManager.GetActiveScene(); var accept = EditorUtility.DisplayDialog("Setup Experience App Scene", string.Format("Setup the current scene ({0}) as your Experience App scene? This will modify the structure of the scene.", scene.name), "OK", "Cancel"); if (!accept) { return; } EditorSceneManager.EnsureUntitledSceneHasBeenSaved("You must save the current scene before continuing."); EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); // Clear the 'appscene' asset bundle from ALL other assets // Only the experience app scene can have this bundle name! foreach (var path in AssetDatabase.GetAssetPathsFromAssetBundle("appscene")) { AssetImporter.GetAtPath(path).SetAssetBundleNameAndVariant(null, null); } // Make sure this is the only open scene scene = EditorSceneManager.OpenScene(scene.path, OpenSceneMode.Single); var app = UnityEngine.Object.FindObjectOfType <ExperienceApp>(); if (app == null) { app = new GameObject("[ExperienceApp]") .AddComponent <ExperienceApp>(); } else { // Move to the root app.gameObject.name = "[ExperienceApp]"; app.transform.SetParentAndIdentity(null); } //attach the experience settings profile to the config if it exists app.LimappConfig.ProfileToApply = Resources.Load <ExperienceProfile>("LimappConfig"); // Ensure the VREmulator is available on the app app.gameObject.GetOrAddComponent <VREmulator>(); // Move all other objects under the ExperienceApp object foreach (var obj in scene.GetRootGameObjects()) { if (obj == app.gameObject) { continue; } obj.transform.parent = app.transform; } // Ensure there is a VRAvatar var vrAvatar = UnityEngine.Object.FindObjectOfType <VRAvatar>(); if (vrAvatar == null) { var prefabAsset = Resources.Load <VRAvatar>("VRAvatar"); vrAvatar = (VRAvatar)PrefabUtility.InstantiatePrefab(prefabAsset); } // Move avatar to the app vrAvatar.transform.SetParentAndIdentity(app.transform); vrAvatar.transform.SetAsFirstSibling(); // Disable the cameras tagged with MainCamera if it isn't part of the VRAvatar foreach (var camera in UnityEngine.Object.FindObjectsOfType <Camera>()) { if (!camera.transform.IsDescendentOf(vrAvatar.transform)) { if (camera.CompareTag("MainCamera")) { camera.gameObject.SetActive(false); Debug.LogWarning("MainCamera was disabled. Use VRAvatar/Head/CenterEye as your main camera", camera); } } } Debug.Log("Setup complete! Please ensure that you use the cameras nested under VRAvatar/Head as your VR cameras."); }
private static string GetHierarchyPath(GameObject gameObject, bool includeScene = true) { if (gameObject == null) { return(String.Empty); } StringBuilder sb; if (_SbPool.Count > 0) { sb = _SbPool.Pop(); sb.Clear(); } else { sb = new StringBuilder(200); } try { if (includeScene) { var sceneName = gameObject.scene.name; if (sceneName == string.Empty) { #if UNITY_2018_3_OR_NEWER var prefabStage = PrefabStageUtility.GetPrefabStage(gameObject); if (prefabStage != null) { sceneName = "Prefab Stage"; } else #endif { sceneName = "Unsaved Scene"; } } sb.Append("<b>" + sceneName + "</b>"); } sb.Append(GetTransformPath(gameObject.transform)); #if false bool isPrefab; #if UNITY_2018_3_OR_NEWER isPrefab = PrefabUtility.GetPrefabAssetType(gameObject.gameObject) != PrefabAssetType.NotAPrefab; #else isPrefab = UnityEditor.PrefabUtility.GetPrefabType(o) == UnityEditor.PrefabType.Prefab; #endif var assetPath = string.Empty; if (isPrefab) { #if UNITY_2018_3_OR_NEWER assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(gameObject); #else assetPath = AssetDatabase.GetAssetPath(gameObject); #endif sb.Append(" (" + System.IO.Path.GetFileName(assetPath) + ")"); } #endif var path = sb.ToString(); sb.Clear(); return(path); } finally { _SbPool.Push(sb); } }
void OnWizardCreate() { EditorUtility.DisplayProgressBar("New Character Wizard", "Checking parameters...", 0.1f); SetUnitPrefab(); EditorUtility.DisplayProgressBar("New Character Wizard", "Creating Resources Subfolder...", 0.2f); // Create root game folder string newGameFolder = GetNewGameFolder(); string resourcesFolder = newGameFolder + "/Resources/" + fileSystemGameName + "/UnitProfile"; // create resources folder CreateFolderIfNotExists(resourcesFolder); AssetDatabase.Refresh(); EditorUtility.DisplayProgressBar("New Character Wizard", "Creating Unit Profile...", 0.3f); UnitProfile asset = ScriptableObject.CreateInstance("UnitProfile") as UnitProfile; EditorUtility.DisplayProgressBar("New Character Wizard", "Configuring Unit Profile...", 0.4f); // setup unit profile properties asset.ResourceName = characterName; asset.CharacterName = characterName; asset.AutomaticPrefabProfile = false; asset.UseInlinePrefabProps = true; // setup unit prefab properties asset.UnitPrefabProps.UnitPrefab = unitPrefab; asset.UnitPrefabProps.ModelPrefab = characterModel; asset.UnitPrefabProps.RotateModel = true; asset.UnitPrefabProps.UseInlineAnimationProps = true; // setup animation properties asset.UnitPrefabProps.AnimationProps = animations; // setup nameplate properties asset.UnitPrefabProps.NamePlateProps.UnitFrameTarget = headBone; asset.UnitPrefabProps.NamePlateProps.OverrideNameplatePosition = true; asset.UnitPrefabProps.NamePlateProps.NameplatePosition = new Vector3(0f, highestYTransform + namePlateHeightAdd, 0f); // set the look position at half the height asset.UnitPrefabProps.NamePlateProps.UnitPreviewCameraLookOffset = new Vector3(0f, highestYTransform / 2f, 0f); // zoom out to 1.25 times the height asset.UnitPrefabProps.NamePlateProps.UnitPreviewCameraPositionOffset = new Vector3(0f, highestYTransform / 2f, highestYTransform * 1.25f); // setup foootstep properties asset.MovementAudioProfileNames.Add(defaultFootstepLoop); EditorUtility.DisplayProgressBar("New Character Wizard", "Saving Unit Profile...", 0.5f); scriptableObjectPath = "Assets" + newGameParentFolder + fileSystemGameName + "/Resources/" + fileSystemGameName + "/UnitProfile/" + GetFileSystemCharactername(characterName) + "Unit.asset"; AssetDatabase.CreateAsset(asset, scriptableObjectPath); AssetDatabase.Refresh(); EditorUtility.DisplayProgressBar("New Character Wizard", "Checking Default Player Unit Setting...", 0.6f); if (setAsDefaultPlayerCharacter == true && systemConfigurationManager != null) { SystemConfigurationManager diskSystemConfigurationManager = PrefabUtility.GetCorrespondingObjectFromSource <SystemConfigurationManager>(systemConfigurationManager); if (diskSystemConfigurationManager != null) { diskSystemConfigurationManager.DefaultPlayerUnitProfileName = characterName; EditorUtility.SetDirty(diskSystemConfigurationManager); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); // this next bit is due to a unity bug? where scene objects are not reimported when modified through script /* * Object realGO = PrefabUtility.GetCorrespondingObjectFromSource(systemConfigurationManager); * string selectedPath = AssetDatabase.GetAssetPath(realGO); * Debug.Log(selectedPath); * AssetDatabase.ImportAsset(selectedPath); */ //EditorApplication.RepaintHierarchyWindow(); //SceneManager.UnloadSceneAsync(SceneManager.GetActiveScene().buildIndex); //Resources.UnloadUnusedAssets(); //SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex, LoadSceneMode.Single); } } EditorUtility.ClearProgressBar(); EditorUtility.DisplayDialog("New Character Wizard", "New Character Wizard Complete! The character UnitProfile can be found at " + scriptableObjectPath, "OK"); }
public static void ExportAvatarBundle() { GameObject obj = Selection.activeGameObject; string error; if (!AvatarCheck.CheckAvatar(obj, out error)) { EditorUtility.DisplayDialog("Export Avatar Bundle", error, "OK"); return; } string fullpath = EditorUtility.SaveFilePanel("Export Avatar Bundle", ".", obj.name, "vsfavatar"); if (fullpath == null || fullpath == "") { return; } string filename = Path.GetFileName(fullpath); bool complete = false; string prefabPath = "Assets/VSFAvatarTemporary.prefab"; try { AssetDatabase.DeleteAsset(prefabPath); if (File.Exists(prefabPath)) { File.Delete(prefabPath); } bool succeededPack = false; PrefabUtility.SaveAsPrefabAsset(obj, prefabPath, out succeededPack); if (!succeededPack) { Debug.Log("Prefab creation failed"); return; } AssetBundleBuild bundleBuild = new AssetBundleBuild(); AssetDatabase.RemoveUnusedAssetBundleNames(); bundleBuild.assetBundleName = filename; bundleBuild.assetNames = new string[] { prefabPath }; bundleBuild.addressableNames = new string[] { "VSFAvatar" }; BuildAssetBundleOptions options = BuildAssetBundleOptions.ForceRebuildAssetBundle | BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.StrictMode; if (obj.GetComponentsInChildren <UnityEngine.Video.VideoPlayer>(true).Length > 0) { Debug.Log("VideoPlayer detected, using uncompressed asset bundle."); options = options | BuildAssetBundleOptions.UncompressedAssetBundle; } BuildPipeline.BuildAssetBundles(Application.temporaryCachePath, new AssetBundleBuild[] { bundleBuild }, options, BuildTarget.StandaloneWindows); if (File.Exists(fullpath)) { File.Delete(fullpath); } File.Move(Application.temporaryCachePath + "/" + filename, fullpath); EditorUtility.DisplayDialog("Export", "Export complete!", "OK"); complete = true; } finally { try { AssetDatabase.DeleteAsset(prefabPath); if (File.Exists(prefabPath)) { File.Delete(prefabPath); } } catch {} if (!complete) { EditorUtility.DisplayDialog("Export", "Export failed! See the console for details.", "OK"); } } }
/// <summary> /// Draw the UI for this tool. /// </summary> void OnGUI() { Object fnt = NGUISettings.ambigiousFont; UIFont uiFont = (fnt as UIFont); NGUIEditorTools.SetLabelWidth(80f); GUILayout.Space(3f); NGUIEditorTools.DrawHeader("Input", true); NGUIEditorTools.BeginContents(); GUILayout.BeginHorizontal(); mType = (FontType)EditorGUILayout.EnumPopup("Type", mType, GUILayout.MinWidth(200f)); GUILayout.Space(18f); GUILayout.EndHorizontal(); Create create = Create.None; if (mType == FontType.ImportedBitmap) { NGUISettings.fontData = EditorGUILayout.ObjectField("Font Data", NGUISettings.fontData, typeof(TextAsset), false) as TextAsset; NGUISettings.fontTexture = EditorGUILayout.ObjectField("Texture", NGUISettings.fontTexture, typeof(Texture2D), false, GUILayout.Width(140f)) as Texture2D; NGUIEditorTools.EndContents(); // Draw the atlas selection only if we have the font data and texture specified, just to make it easier EditorGUI.BeginDisabledGroup(NGUISettings.fontData == null || NGUISettings.fontTexture == null); { NGUIEditorTools.DrawHeader("Output", true); NGUIEditorTools.BeginContents(); ComponentSelector.Draw <UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false); NGUIEditorTools.EndContents(); } EditorGUI.EndDisabledGroup(); if (NGUISettings.fontData == null) { EditorGUILayout.HelpBox("To create a font from a previously exported FNT file, you need to use BMFont on " + "Windows or your choice of Glyph Designer or the less expensive bmGlyph on the Mac.\n\n" + "Either of these tools will create a FNT file for you that you will drag & drop into the field above.", MessageType.Info); } else if (NGUISettings.fontTexture == null) { EditorGUILayout.HelpBox("When exporting your font, you should get two files: the FNT, and the texture. Only one texture can be used per font.", MessageType.Info); } else if (NGUISettings.atlas == null) { EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " + "labels using this font will generate an extra draw call.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info); } EditorGUI.BeginDisabledGroup(NGUISettings.fontData == null || NGUISettings.fontTexture == null); { GUILayout.BeginHorizontal(); GUILayout.Space(20f); if (GUILayout.Button("Create the Font")) { create = Create.Import; } GUILayout.Space(20f); GUILayout.EndHorizontal(); } EditorGUI.EndDisabledGroup(); } else { GUILayout.BeginHorizontal(); if (NGUIEditorTools.DrawPrefixButton("Source")) { ComponentSelector.Show <Font>(OnUnityFont, new string[] { ".ttf", ".otf" }); } Font ttf = EditorGUILayout.ObjectField(NGUISettings.ambigiousFont as Font, typeof(Font), false) as Font; GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); { NGUISettings.fontSize = EditorGUILayout.IntField("Size", NGUISettings.fontSize, GUILayout.Width(120f)); if (mType == FontType.Dynamic) { NGUISettings.fontStyle = (FontStyle)EditorGUILayout.EnumPopup(NGUISettings.fontStyle); GUILayout.Space(18f); } } GUILayout.EndHorizontal(); // Choose the font style if there are multiple faces present if (mType == FontType.GeneratedBitmap) { if (!FreeType.isPresent) { if (Application.platform != RuntimePlatform.WindowsEditor) { EditorGUILayout.HelpBox("Built-in bitmap font generation is only available on Windows platforms.", MessageType.Error); } else { EditorGUILayout.HelpBox("Assets/Editor/FreeType.dll is missing", MessageType.Error); GUILayout.BeginHorizontal(); GUILayout.Space(20f); if (GUILayout.Button("Find FreeType.dll")) { string path = EditorUtility.OpenFilePanel("Find FreeType.dll", "Assets", "dll"); if (!string.IsNullOrEmpty(path)) { if (System.IO.Path.GetFileName(path) == "FreeType.dll") { NGUISettings.pathToFreeType = path; } else { Debug.LogError("The library must be named 'FreeType'"); } } } GUILayout.Space(20f); GUILayout.EndHorizontal(); } } else if (ttf != null) { string[] faces = FreeType.GetFaces(ttf); if (faces != null) { if (mFaceIndex >= faces.Length) { mFaceIndex = 0; } if (faces.Length > 1) { GUILayout.Label("Style", EditorStyles.boldLabel); for (int i = 0; i < faces.Length; ++i) { GUILayout.BeginHorizontal(); GUILayout.Space(10f); if (DrawOption(i == mFaceIndex, " " + faces[i])) { mFaceIndex = i; } GUILayout.EndHorizontal(); } } } GUILayout.Label("Characters", EditorStyles.boldLabel); CharacterMap cm = characterMap; GUILayout.BeginHorizontal(GUILayout.Width(100f)); GUILayout.BeginVertical(); GUI.changed = false; if (DrawOption(cm == CharacterMap.Numeric, " Numeric")) { cm = CharacterMap.Numeric; } if (DrawOption(cm == CharacterMap.Ascii, " ASCII")) { cm = CharacterMap.Ascii; } if (DrawOption(cm == CharacterMap.Latin, " Latin")) { cm = CharacterMap.Latin; } if (DrawOption(cm == CharacterMap.Custom, " Custom")) { cm = CharacterMap.Custom; } if (GUI.changed) { characterMap = cm; } GUILayout.EndVertical(); EditorGUI.BeginDisabledGroup(cm != CharacterMap.Custom); { if (cm != CharacterMap.Custom) { string chars = ""; if (cm == CharacterMap.Ascii) { for (int i = 33; i < 127; ++i) { chars += System.Convert.ToChar(i); } } else if (cm == CharacterMap.Numeric) { chars = "01234567890"; } else if (cm == CharacterMap.Latin) { for (int i = 33; i < 127; ++i) { chars += System.Convert.ToChar(i); } for (int i = 161; i < 256; ++i) { chars += System.Convert.ToChar(i); } } NGUISettings.charsToInclude = chars; } GUI.changed = false; string text = NGUISettings.charsToInclude; if (cm == CharacterMap.Custom) { text = EditorGUILayout.TextArea(text, GUI.skin.textArea, GUILayout.Height(80f), GUILayout.Width(Screen.width - 100f)); } else { GUILayout.Label(text, GUI.skin.textArea, GUILayout.Height(80f), GUILayout.Width(Screen.width - 100f)); } if (GUI.changed) { string final = ""; for (int i = 0; i < text.Length; ++i) { char c = text[i]; if (c < 33) { continue; } string s = c.ToString(); if (!final.Contains(s)) { final += s; } } if (final.Length > 0) { char[] chars = final.ToCharArray(); System.Array.Sort(chars); final = new string(chars); } else { final = ""; } NGUISettings.charsToInclude = final; } } EditorGUI.EndDisabledGroup(); GUILayout.EndHorizontal(); } } NGUIEditorTools.EndContents(); if (mType == FontType.Dynamic) { EditorGUI.BeginDisabledGroup(ttf == null); GUILayout.BeginHorizontal(); GUILayout.Space(20f); if (GUILayout.Button("Create the Font")) { create = Create.Dynamic; } GUILayout.Space(20f); GUILayout.EndHorizontal(); EditorGUI.EndDisabledGroup(); #if UNITY_3_5 EditorGUILayout.HelpBox("Dynamic fonts require Unity 4.0 or higher.", MessageType.Error); #else // Helpful info if (ttf == null) { EditorGUILayout.HelpBox("You don't have to create a UIFont to use dynamic fonts. You can just reference the Unity Font directly on the label.", MessageType.Info); } EditorGUILayout.HelpBox("Please note that dynamic fonts can't be made a part of an atlas, and using dynamic fonts will result in at least one extra draw call.", MessageType.Warning); #endif } else { bool isBuiltIn = (ttf != null) && string.IsNullOrEmpty(UnityEditor.AssetDatabase.GetAssetPath(ttf)); // Draw the atlas selection only if we have the font data and texture specified, just to make it easier EditorGUI.BeginDisabledGroup(ttf == null || isBuiltIn || !FreeType.isPresent); { NGUIEditorTools.DrawHeader("Output", true); NGUIEditorTools.BeginContents(); ComponentSelector.Draw <UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false); NGUIEditorTools.EndContents(); if (ttf == null) { EditorGUILayout.HelpBox("You can create a bitmap font by specifying a dynamic font to use as the source.", MessageType.Info); } else if (isBuiltIn) { EditorGUILayout.HelpBox("You chose an embedded font. You can't create a bitmap font from an embedded resource.", MessageType.Warning); } else if (NGUISettings.atlas == null) { EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " + "labels using this font will generate an extra draw call.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info); } GUILayout.BeginHorizontal(); GUILayout.Space(20f); if (GUILayout.Button("Create the Font")) { create = Create.Bitmap; } GUILayout.Space(20f); GUILayout.EndHorizontal(); } EditorGUI.EndDisabledGroup(); } } if (create == Create.None) { return; } // Open the "Save As" file dialog string prefabPath = EditorUtility.SaveFilePanelInProject("Save As", "New Font.prefab", "prefab", "Save font as..."); if (string.IsNullOrEmpty(prefabPath)) { return; } // Load the font's prefab GameObject go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject; Object prefab = null; string fontName; // Font doesn't exist yet if (go == null || go.GetComponent <UIFont>() == null) { // Create a new prefab for the atlas prefab = PrefabUtility.CreateEmptyPrefab(prefabPath); fontName = prefabPath.Replace(".prefab", ""); fontName = fontName.Substring(prefabPath.LastIndexOfAny(new char[] { '/', '\\' }) + 1); // Create a new game object for the font go = new GameObject(fontName); uiFont = go.AddComponent <UIFont>(); } else { uiFont = go.GetComponent <UIFont>(); fontName = go.name; } if (create == Create.Dynamic) { uiFont.atlas = null; uiFont.dynamicFont = NGUISettings.dynamicFont; uiFont.dynamicFontStyle = NGUISettings.fontStyle; uiFont.defaultSize = NGUISettings.fontSize; } else if (create == Create.Import) { Material mat = null; if (NGUISettings.atlas != null) { // Add the font's texture to the atlas UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, NGUISettings.fontTexture); } else { // Create a material for the font string matPath = prefabPath.Replace(".prefab", ".mat"); mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material; // If the material doesn't exist, create it if (mat == null) { Shader shader = Shader.Find("Unlit/Transparent Colored"); mat = new Material(shader); // Save the material AssetDatabase.CreateAsset(mat, matPath); AssetDatabase.Refresh(); // Load the material so it's usable mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material; } mat.mainTexture = NGUISettings.fontTexture; } uiFont.dynamicFont = null; BMFontReader.Load(uiFont.bmFont, NGUITools.GetHierarchy(uiFont.gameObject), NGUISettings.fontData.bytes); if (NGUISettings.atlas == null) { uiFont.atlas = null; uiFont.material = mat; } else { uiFont.spriteName = NGUISettings.fontTexture.name; uiFont.atlas = NGUISettings.atlas; } NGUISettings.fontSize = uiFont.defaultSize; } else if (create == Create.Bitmap) { // Create the bitmap font BMFont bmFont; Texture2D tex; if (FreeType.CreateFont( NGUISettings.dynamicFont, NGUISettings.fontSize, mFaceIndex, NGUISettings.charsToInclude, out bmFont, out tex)) { uiFont.bmFont = bmFont; tex.name = fontName; if (NGUISettings.atlas != null) { // Add this texture to the atlas and destroy it UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, tex); NGUITools.DestroyImmediate(tex); NGUISettings.fontTexture = null; tex = null; uiFont.atlas = NGUISettings.atlas; uiFont.spriteName = fontName; } else { string texPath = prefabPath.Replace(".prefab", ".png"); string matPath = prefabPath.Replace(".prefab", ".mat"); byte[] png = tex.EncodeToPNG(); FileStream fs = File.OpenWrite(texPath); fs.Write(png, 0, png.Length); fs.Close(); // See if the material already exists Material mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material; // If the material doesn't exist, create it if (mat == null) { Shader shader = Shader.Find("Unlit/Transparent Colored"); mat = new Material(shader); // Save the material AssetDatabase.CreateAsset(mat, matPath); AssetDatabase.Refresh(); // Load the material so it's usable mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material; } else { AssetDatabase.Refresh(); } // Re-load the texture tex = AssetDatabase.LoadAssetAtPath(texPath, typeof(Texture2D)) as Texture2D; // Assign the texture mat.mainTexture = tex; NGUISettings.fontTexture = tex; uiFont.atlas = null; uiFont.material = mat; } } else { return; } } if (prefab != null) { // Update the prefab PrefabUtility.ReplacePrefab(go, prefab); DestroyImmediate(go); AssetDatabase.Refresh(); // Select the atlas go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject; uiFont = go.GetComponent <UIFont>(); } if (uiFont != null) { NGUISettings.ambigiousFont = uiFont; } MarkAsChanged(); Selection.activeGameObject = go; }
// --------------------------------------------------------------------- public string EndCapture(Texture2D[] SpriteTextures) { #if UNITY_WEBPLAYER Debug.LogError("In WEB_PLAYER mode, you cannot run the FXMaker."); Debug.Break(); return(null); #else int nTexSize = m_nResultTextureSize; int nCapSize = m_nResultCaptureSize; int nMaxCount = (nTexSize / nCapSize) * (nTexSize / nCapSize); int nTexHeight = (m_nSaveFrameCount <= nMaxCount / 2 ? nTexSize / 2 : nTexSize); Texture2D spriteTexture = new Texture2D(nTexSize, nTexHeight, TextureFormat.ARGB32, false); int nSaveCount = 0; for (int x = 0; x < spriteTexture.width; x++) { for (int y = 0; y < spriteTexture.height; y++) { spriteTexture.SetPixel(x, y, Color.black); } } for (int n = m_nSkipFrameCount; n < m_nTotalFrameCount; n++, nSaveCount++) { Color[] srcColors = SpriteTextures[n].GetPixels(0); if (m_ShaderType == SHADER_TYPE.ALPHA_BLENDED || m_ShaderType == SHADER_TYPE.ALPHA_BLENDED_MOBILE) { srcColors = NgAtlas.ConvertAlphaTexture(srcColors, true, FXMakerOption.inst.m_AlphaWeightCurve, 1, 1, 1); } spriteTexture.SetPixels(((nSaveCount) % (nTexSize / nCapSize)) * nCapSize, nTexHeight - (((nSaveCount) / (nTexSize / nCapSize) + 1) * nCapSize), nCapSize, nCapSize, srcColors); Object.DestroyImmediate(SpriteTextures[n]); } byte[] bytes = spriteTexture.EncodeToPNG(); string texBasePath; if (FXMakerLayout.m_bDevelopState) { texBasePath = FXMakerMain.inst.GetResourceDir(FXMakerMain.TOOLDIR_TYPE.SPRITE_TOOL); } else { texBasePath = FXMakerMain.inst.GetResourceDir(FXMakerMain.TOOLDIR_TYPE.SPRITE_USER); } string pathTexture = NgTexture.UniqueTexturePath(texBasePath, m_SelectedPrefabName); // save texture File.WriteAllBytes(pathTexture, bytes); AssetDatabase.Refresh(); NgTexture.ReimportTexture(pathTexture, m_bGUITexture, m_wrapMode, m_filterMode, m_anisoLevel, m_nSpriteTextureSizes[(int)m_fSpriteTextureIndex], m_SpriteTextureFormat[(int)m_fSpriteTextureFormatIdx]); Object.DestroyImmediate(spriteTexture); // Create Prefab if (m_bCreatePrefab) { string pathMaterial = CreateMaterial(pathTexture); Material newMat = (Material)AssetDatabase.LoadAssetAtPath(pathMaterial, typeof(Material)); GameObject newPrefab = (GameObject)Instantiate(FXMakerMain.inst.m_FXMakerSpritePrefab); newPrefab.transform.rotation = Quaternion.identity; newPrefab.renderer.material = newMat; NcSpriteAnimation spriteCom = newPrefab.GetComponent <NcSpriteAnimation>(); spriteCom.m_bBuildSpriteObj = true; spriteCom.m_nFrameCount = m_nSaveFrameCount; spriteCom.m_fFps = m_nResultFps; spriteCom.m_nTilingX = m_nResultTextureSize / m_nResultCaptureSize; spriteCom.m_nTilingY = (m_nSaveFrameCount <= spriteCom.m_nTilingX * spriteCom.m_nTilingX / 2 ? spriteCom.m_nTilingX / 2 : spriteCom.m_nTilingX); spriteCom.m_PlayMode = m_PlayMode; spriteCom.m_bLoop = m_bLoop; spriteCom.m_nLoopStartFrame = 0; spriteCom.m_nLoopFrameCount = spriteCom.m_nFrameCount; spriteCom.m_nLoopingCount = 0; spriteCom.m_bAutoDestruct = !m_bLoop; NcCurveAnimation curveCom = newPrefab.GetComponent <NcCurveAnimation>(); if (curveCom.GetCurveInfoCount() != 3) { Debug.LogError("FXMakerMain.inst.m_FxmSpritePrefab : curveCom Count Error!!!"); } curveCom.GetCurveInfo(0).m_bEnabled = false; // both curveCom.GetCurveInfo(1).m_bEnabled = false; // fadein curveCom.GetCurveInfo(2).m_bEnabled = false; // fadeout curveCom.m_bAutoDestruct = false; curveCom.m_fDurationTime = spriteCom.GetDurationTime(); if (m_bFadeIn && m_bFadeOut) { curveCom.GetCurveInfo(0).m_bEnabled = true; } else { if (m_bFadeIn) { curveCom.GetCurveInfo(1).m_bEnabled = true; } if (m_bFadeOut) { curveCom.GetCurveInfo(2).m_bEnabled = true; } } string basePath = AssetDatabase.GetAssetPath(FXMakerMain.inst.GetOriginalEffectPrefab()); string prefabPath = UniquePrefabPath(NgFile.TrimFilenameExt(basePath)); GameObject createPrefab = PrefabUtility.CreatePrefab(prefabPath, newPrefab); Destroy(newPrefab); // Create Thumb CreateSpriteThumb(createPrefab, pathTexture); AssetDatabase.SaveAssets(); return(prefabPath); } else { return(pathTexture); } #endif }
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { foreach (string assetPath in importedAssets) { if (Path.GetExtension(assetPath) == ".meta") { continue; } string assetFileName = Path.GetFileName(assetPath); string[] split = assetFileName.Split(templateSeperator); if (split.Length != 3) { continue; } string uuid = split[1]; string assetName = split[2]; string assetFolder = Path.GetDirectoryName(assetPath); if (assetPath.StartsWith(processingFolder)) //Looking for the copied .fbx file that resides in the projects processing/prefab folder { if (!assetPath.EndsWith(".fbx", StringComparison.OrdinalIgnoreCase)) //only check if .fbx is in the processing folder { continue; } GameObject modelAsset = AssetDatabase.LoadAssetAtPath <GameObject> (assetPath); //LOADING AN ASSET string jsonPath = Path.Combine(assetBundlesFolder, uuid + ".json"); if (!File.Exists(jsonPath)) { Debug.LogError("SKIPPING - The JSON file did not exist at path: " + jsonPath); continue; } ModelImporter modelImporter = ModelImporter.GetAtPath(assetPath) as ModelImporter; string jsonTxt = File.ReadAllText(jsonPath); AssetBundleUserJson userPrefs = (AssetBundleUserJson)JsonUtility.FromJson(jsonTxt, typeof(AssetBundleUserJson)); //RE-IMPORTED SECTION (SECOND-IMPORT): if (!Directory.Exists(prefabsFolder)) { Directory.CreateDirectory(prefabsFolder); } string modelFileName = Path.GetFileNameWithoutExtension(assetPath); string destinationPath = Path.Combine(prefabsFolder, modelFileName + ".prefab"); GameObject model = (GameObject)PrefabUtility.InstantiatePrefab(modelAsset); GameObject real = GameObject.Instantiate(model); //this is a game object that we can re-arange and change parenting or objects, then save as the original prefab later on real.SetActive(true); real.name = model.name; //remove "(clone) or any other discrepancies from name" GameObject.DestroyImmediate(model); //destroy the prefab as it will be overwritten by "real" var defaultController = Resources.Load <RuntimeAnimatorController>("DefaultAnimationController"); if (defaultController != null) { real.transform.root.GetComponentInChildren <Animator> ().runtimeAnimatorController = defaultController; } //Build the prop and set all data arrays var buildProp = real.AddComponent <BuildProp> (); buildProp.CreateEmptyContianers(real.name); GameObject.DestroyImmediate(buildProp); //no long need this component, so destroy it. string blenderJsonPath = Path.Combine(assetFolder, "blender.json"); Dictionary <string, MaterialsJson> materialsJson = null; if (File.Exists(blenderJsonPath)) { BlenderJsonObject blenderJsonArray = JsonUtility.FromJson <BlenderJsonObject> ( File.ReadAllText(blenderJsonPath) ); materialsJson = BuildMaterialsDict(blenderJsonArray.materials); } var childrenRenderers = real.GetComponentsInChildren <Renderer>(); foreach (Renderer renderer in childrenRenderers) { if (renderer != null) { renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On; renderer.receiveShadows = true; var material = renderer.sharedMaterial; var mainColor = material.GetColor("_Color"); mainColor.a = 1.0f; //always do this, just because unity is weird and seemingly random alpha values always appear material.SetColor("_Color", mainColor); if (materialsJson != null) { //THE NEW WAY (USING BLENDER MATERIALS JSON) var was = Path.GetFileName(AssetDatabase.GetAssetPath(material.mainTexture)); var materialName = material.name; // Path.GetFileName (AssetDatabase.GetAssetPath (material.mainTexture)); //takes a full path to an texture asset, and returs the filename with extension (which is used as key for materials json) if (material.mainTexture != null) { materialName = Path.GetFileName(AssetDatabase.GetAssetPath(material.mainTexture)); //takes a full path to an texture asset, and returs the filename with extension (which is used as key for materials json) } if (materialsJson.ContainsKey(materialName)) { var blenderMaterial = materialsJson [materialName]; Texture2D diffTex = null; Texture2D bumpTex = null; Texture2D specularTex = null; Texture2D emissionTex = null; bool enableAlpha = false; float emit_factor = 0; var use_map_color_diffuse = false; var use_map_bump = false; var use_map_specular = false; var use_map_emit = false; foreach (var slot in blenderMaterial.texture_slots) //check all slots to see if there are any spec or emmit textures { if (slot.use_map_color_diffuse) { //Debug.Log("use_map_color_diffuse " + slot.filename); //var texPath = AssetDatabase.GetAssetPath (material.mainTexture); var texPath = Path.Combine(Path.GetDirectoryName(assetPath), slot.filename); if (File.Exists(texPath)) { var folder = Path.GetDirectoryName(texPath); diffTex = AssetDatabase.LoadAssetAtPath(Path.Combine(folder, slot.filename), typeof(Texture2D)) as Texture2D; TextureImporter A = (TextureImporter)AssetImporter.GetAtPath(Path.Combine(folder, slot.filename)); enableAlpha = blenderMaterial.use_transparency && A.DoesSourceTextureHaveAlpha(); } } if (slot.use_map_normal) { //Debug.Log("use_map_normal " + slot.filename); //var texPath = AssetDatabase.GetAssetPath (material.mainTexture); var texPath = Path.Combine(Path.GetDirectoryName(assetPath), slot.filename); if (File.Exists(texPath)) { var folder = Path.GetDirectoryName(texPath); bumpTex = AssetDatabase.LoadAssetAtPath(Path.Combine(folder, slot.filename), typeof(Texture2D)) as Texture2D; } } if (slot.use_map_specular) { //Debug.Log("use_map_specular " + slot.filename); //var texPath = AssetDatabase.GetAssetPath (material.mainTexture); var texPath = Path.Combine(Path.GetDirectoryName(assetPath), slot.filename); if (File.Exists(texPath)) { var folder = Path.GetDirectoryName(texPath); specularTex = AssetDatabase.LoadAssetAtPath(Path.Combine(folder, slot.filename), typeof(Texture2D)) as Texture2D; } } if (slot.use_map_emit) { //Debug.Log("use_map_emit " + slot.filename); //var texPath = AssetDatabase.GetAssetPath (material.mainTexture); var texPath = Path.Combine(Path.GetDirectoryName(assetPath), slot.filename); if (File.Exists(texPath)) { var folder = Path.GetDirectoryName(texPath); emissionTex = AssetDatabase.LoadAssetAtPath(Path.Combine(folder, slot.filename), typeof(Texture2D)) as Texture2D; } emit_factor = slot.emit_factor; } use_map_color_diffuse |= slot.use_map_color_diffuse; use_map_bump |= slot.use_map_normal; use_map_specular |= slot.use_map_specular; use_map_emit |= slot.use_map_emit; } var specIsBlack = (blenderMaterial.specular_color.r * blenderMaterial.specular_intensity) == 0 && (blenderMaterial.specular_color.g * blenderMaterial.specular_intensity) == 0 && (blenderMaterial.specular_color.b * blenderMaterial.specular_intensity) == 0; if (!specIsBlack || use_map_specular) { material.shader = Shader.Find("Standard (Specular setup)"); //the default fallback shader material.SetColor("_SpecColor", new Color( blenderMaterial.specular_color.r * blenderMaterial.specular_intensity * 0.25f, //default values are way too high for Standard shader so multiply by 0.25 blenderMaterial.specular_color.g * blenderMaterial.specular_intensity * 0.25f, blenderMaterial.specular_color.b * blenderMaterial.specular_intensity * 0.25f )); } if (use_map_color_diffuse) //set all white and adjust brightness based on diffuse intensity set from blender { material.SetColor("_Color", new Color( blenderMaterial.diffuse_intensity, blenderMaterial.diffuse_intensity, blenderMaterial.diffuse_intensity, blenderMaterial.alpha )); } else { material.SetColor("_Color", new Color( // has no texture, thus pass through the color and adjust on diffuse intensity set from blender mainColor.r * blenderMaterial.diffuse_intensity, mainColor.g * blenderMaterial.diffuse_intensity, mainColor.b * blenderMaterial.diffuse_intensity, blenderMaterial.alpha )); if (blenderMaterial.use_transparency) //has no texture but alpha was set, so ensure to honor that { enableAlpha = true; } } if (enableAlpha) //change to opaque https://sassybot.com/blog/swapping-rendering-mode-in-unity-5-0/ { material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.EnableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = 3000; } else //OPAQUE { material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = -1; } if (use_map_color_diffuse) { material.SetTexture("_MainTex", diffTex); } if (use_map_bump) { material.SetTexture("_BumpMap", bumpTex); } if (use_map_emit) { material.EnableKeyword("_EMISSION"); //You must enable the correct Keywords for your required Standard Shader variant material.SetTexture("_EmissionMap", emissionTex); material.SetColor("_EmissionColor", new Color( emit_factor, emit_factor, emit_factor )); } if (use_map_specular) { material.EnableKeyword("_SPECGLOSSMAP"); //You must enable the correct Keywords for your required Standard Shader variant material.SetTexture("_SpecGlossMap", specularTex); } material.SetFloat("_GlossMapScale", blenderMaterial.specular_hardness / 511f); material.SetFloat("_Glossiness", blenderMaterial.specular_hardness / 511f); material.SetFloat("_Shininess", blenderMaterial.specular_hardness / 511f); //synonmus with _Glossiness if using legacy shaders if (!use_map_specular && !use_map_emit) { if (blenderMaterial.key.ToLower().Contains("hair")) { material.shader = Shader.Find("Custom/Standard Two Sided Soft Blend"); material.SetFloat("_Cutoff", 0.05f); } else if ( blenderMaterial.key.ToLower().Contains("eye") && ( blenderMaterial.key.ToLower().Contains("lash") || blenderMaterial.key.ToLower().Contains("brow") )) //if its hair sprites { material.shader = Shader.Find("Sprites/Default"); continue; //it's no longer a stander shader, nothing more to be done } } } } else { /* * material.shader = Shader.Find ("Standard (Specular setup)"); //the default fallback shader * //THE OLD WAY - USE KEYWORDS IN FILE NAME TO CONTROL SHADER KEYWORDS * * var color222 = material.GetColor ("_Color"); * * color222.a = 1.0f; //always do this, just because unity is weird and seemingly random alpha values always appear * material.SetColor ("_Color", color222); * * if (material.mainTexture != null) { * * string path = AssetDatabase.GetAssetPath (material.mainTexture); * TextureImporter A = (TextureImporter)AssetImporter.GetAtPath (path); * * if (!A.DoesSourceTextureHaveAlpha ()) {//change to opaque https://sassybot.com/blog/swapping-rendering-mode-in-unity-5-0/ * material.SetInt ("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); * material.SetInt ("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); * material.SetInt ("_ZWrite", 1); * material.DisableKeyword ("_ALPHATEST_ON"); * material.DisableKeyword ("_ALPHABLEND_ON"); * material.DisableKeyword ("_ALPHAPREMULTIPLY_ON"); * material.renderQueue = -1; * } * * var matTextureName = material.mainTexture.name.ToLower (); * //Debug.Log ("MAT NAME " + matTextureName); * var texPath = AssetDatabase.GetAssetPath (material.mainTexture); * var texName = Path.GetFileNameWithoutExtension (texPath); * * //Debug.Log ("matTextureName" + matTextureName); * //Debug.Log ("Texture Path" + texPath); * * Texture specularTex = GetFileByKeywords (texPath, new[] { * "_Spec", * "_spec", * "_Specularity", * "_specularity", * "_Specular", * "_specular" * }); * Texture metallicTex = GetFileByKeywords (texPath, new[] { "_Metallic", "_metallic" }); * * if (specularTex != null) { * //Debug.Log ("JUST SET SPECULAR SETUP!! " + specularTex); * material.shader = Shader.Find ("Standard (Specular setup)"); * material.EnableKeyword ("_SPECGLOSSMAP"); //You must enable the correct Keywords for your required Standard Shader variant * material.SetTexture ("_SpecGlossMap", specularTex); * material.SetColor ("_SpecColor", Color.white); * } else { * if (metallicTex != null) { * material.EnableKeyword ("_METALLICGLOSSMAP"); //You must enable the correct Keywords for your required Standard Shader variant * material.SetTexture ("_MetallicGlossMap", metallicTex); * } * } * * Texture emissionTex = GetFileByKeywords (texPath, new[] { "_Emission", "_emission" }); * if (emissionTex != null) { * material.EnableKeyword ("_EMISSION"); //You must enable the correct Keywords for your required Standard Shader variant * material.SetTexture ("_EmissionMap", emissionTex); * material.SetColor ("_EmissionColor", Color.white); * } * * if (specularTex == null && emissionTex == null) { * if (matTextureName.Contains ("_hair")) { * material.shader = Shader.Find ("Custom/Standard Two Sided Soft Blend"); * material.SetFloat ("_Cutoff", 0.05f); * } else if ( * matTextureName.Contains ("eyelash") || * matTextureName.Contains ("eyebrow")) { //if its hair sprites * material.shader = Shader.Find ("Sprites/Default"); * continue; //it's no longer a stander shader, nothing more to be done * } * } * } * * * if (material.HasProperty ("_Mode") && material.GetFloat ("_Mode").Equals (3)) { //if the exported material has transparency * //Debug.Log ("MODE 3 " + material); * if (color222.a >= 0.9f) { //because blender/unity are weird, and setting blender to 1 results in unity using opaque mode * color222.a = 1.0f; * material.SetColor ("_Color", color222); * } * //material.SetFloat("_Mode", 3); * //material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); * //material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); * //material.SetInt("_ZWrite", 0); * //material.DisableKeyword("_ALPHATEST_ON"); * //material.EnableKeyword("_ALPHABLEND_ON"); * //material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); * //material.renderQueue = 3000; * } */ } //var shaderParams = renderer.gameObject.AddComponent<RendererShaderParams> (); //shaderParams.StoreParams (); //NOW USING RendererShaderParams.StoreAllRenderers (real); } } RendererShaderParams.StoreAllRenderers(real); if (modelImporter.userData.Contains(processedTag)) { string json = JsonUtility.ToJson(userPrefs); using (StreamWriter sr = new StreamWriter(jsonPath)) // Create the file. { sr.WriteLine(json); } } PrefabUtility.SaveAsPrefabAsset(real, destinationPath); GameObject.DestroyImmediate(real); } else if (assetPath.StartsWith(prefabsFolder)) //ASSET BUNDLE FINAL PROCESSING { var assetImport = AssetImporter.GetAtPath(assetPath); assetImport.SetAssetBundleNameAndVariant(Path.GetFileNameWithoutExtension(assetPath), assetBundleVariant); } else if (assetPath.StartsWith(assetBundlesFolder)) //ASSET BUNDLE FINAL PROCESSING { if (!Path.GetExtension(assetPath).Contains(assetBundleVariant)) { continue; //might be a .meta file, just ignore it } var rootObjs = new List <GameObject>(); foreach (var item in UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects()) { if (item.activeSelf) //only store active go's, so that we may disable them during portrait pictures, them re-enable them { rootObjs.Add(item); } } string assetDestFolder = Path.Combine(assetBundlesFolder, Path.GetFileNameWithoutExtension(assetPath).ToLower()); string jsonPath = Path.Combine(assetFolder, uuid + ".json"); if (!File.Exists(jsonPath)) { if (Path.GetDirectoryName(assetPath).Equals(assetBundlesFolder)) { if (Directory.Exists(assetDestFolder)) { FileUtil.DeleteFileOrDirectory(Path.Combine(assetDestFolder, assetFileName)); File.Move(assetPath, Path.Combine(assetDestFolder, assetFileName)); var thumbnailFolderAbs = Path.Combine(assetDestFolder, "thumbnails"); TakePortraitPictures(assetFileName, rootObjs, thumbnailFolderAbs); //update the portrait pictures AssetDatabase.Refresh(); continue; } } else { continue; } Debug.LogWarning("SKIPPING - The JSON file did not exist at path: " + jsonPath); continue; } string jsonTxt = File.ReadAllText(jsonPath); AssetBundleUserJson userPrefs = (AssetBundleUserJson)JsonUtility.FromJson(jsonTxt, typeof(AssetBundleUserJson)); File.Delete(jsonPath); //no longer needed var to = Path.Combine(assetDestFolder, assetFileName); if (!Directory.Exists(Path.GetDirectoryName(to))) { Directory.CreateDirectory(Path.GetDirectoryName(to)); } if (File.Exists(to)) { File.Delete(to); } FileUtil.MoveFileOrDirectory(assetPath, to); DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(assetPath)); FileInfo[] info = dir.GetFiles(Path.GetFileNameWithoutExtension(assetFileName) + ".*"); foreach (FileInfo f in info) { File.Delete(f.FullName); } var thumbnailFolder = Path.Combine(assetDestFolder, "thumbnails"); TakePortraitPictures(assetFileName, rootObjs, thumbnailFolder); //take the initial portrait pictures //copy the .blend character file to the final assetbundle directory if it exists DirectoryInfo dir_blend = new DirectoryInfo(userPrefs.characterFolder); FileInfo blendInfo = dir_blend.GetFiles(Path.GetFileNameWithoutExtension(assetName) + ".blend").FirstOrDefault(); if (blendInfo == null) { Debug.LogWarning(String.Format("{0}.blend file could be copied.", Path.GetFileNameWithoutExtension(assetName))); } else { ZipFile.Compress(new FileInfo(blendInfo.FullName)); if (File.Exists(blendInfo.FullName + ".gz")) { var path_blend_gz = Path.Combine(assetDestFolder, Path.GetFileNameWithoutExtension(assetFileName) + ".blend.gz"); FileUtil.MoveFileOrDirectory(blendInfo.FullName + ".gz", path_blend_gz); } } AssetDatabase.Refresh(); AnimPrepAssetBuilder.ShowExplorer(assetDestFolder); } else { Debug.LogWarning(assetPath + " - WAS NOT A MEMBER OF FOLDERS: " + assetBundlesFolder + " - OR - " + processingFolder); } EditorUtility.UnloadUnusedAssetsImmediate(); System.GC.Collect(); } }
public static void OnPostProcessScene() { // find all NetworkIdentities in all scenes // => can't limit it to GetActiveScene() because that wouldn't work // for additive scene loads (the additively loaded scene is never // the active scene) // => ignore DontDestroyOnLoad scene! this avoids weird situations // like in NetworkZones when we destroy the local player and // load another scene afterwards, yet the local player is still // in the FindObjectsOfType result with scene=DontDestroyOnLoad // for some reason // => OfTypeAll so disabled objects are included too // => Unity 2019 returns prefabs here too, so filter them out. IEnumerable <NetworkIdentity> identities = Resources.FindObjectsOfTypeAll <NetworkIdentity>() .Where(identity => identity.gameObject.hideFlags != HideFlags.NotEditable && identity.gameObject.hideFlags != HideFlags.HideAndDontSave && identity.gameObject.scene.name != "DontDestroyOnLoad" && !PrefabUtility.IsPartOfPrefabAsset(identity.gameObject)); foreach (NetworkIdentity identity in identities) { // if we had a [ConflictComponent] attribute that would be better than this check. // also there is no context about which scene this is in. if (identity.GetComponent <NetworkManager>() != null) { Debug.LogError("NetworkManager has a NetworkIdentity component. This will cause the NetworkManager object to be disabled, so it is not recommended."); } // not spawned before? // OnPostProcessScene is called after additive scene loads too, // and we don't want to set main scene's objects inactive again if (!identity.isClient && !identity.isServer) { // valid scene object? // otherwise it might be an unopened scene that still has null // sceneIds. builds are interrupted if they contain 0 sceneIds, // but it's still possible that we call LoadScene in Editor // for a previously unopened scene. // (and only do SetActive if this was actually a scene object) if (identity.sceneId != 0) { // set scene hash identity.SetSceneIdSceneHashPartInternal(); // disable it // note: NetworkIdentity.OnDisable adds itself to the // spawnableObjects dictionary (only if sceneId != 0) identity.gameObject.SetActive(false); // safety check for prefabs with more than one NetworkIdentity #if UNITY_2018_2_OR_NEWER GameObject prefabGO = PrefabUtility.GetCorrespondingObjectFromSource(identity.gameObject) as GameObject; #else GameObject prefabGO = PrefabUtility.GetPrefabParent(identity.gameObject) as GameObject; #endif if (prefabGO) { #if UNITY_2018_3_OR_NEWER GameObject prefabRootGO = prefabGO.transform.root.gameObject; #else GameObject prefabRootGO = PrefabUtility.FindPrefabRoot(prefabGO); #endif if (prefabRootGO) { if (prefabRootGO.GetComponentsInChildren <NetworkIdentity>().Length > 1) { Debug.LogWarningFormat("Prefab '{0}' has several NetworkIdentity components attached to itself or its children, this is not supported.", prefabRootGO.name); } } } } // throwing an exception would only show it for one object // because this function would return afterwards. else { Debug.LogError("Scene " + identity.gameObject.scene.path + " needs to be opened and resaved, because the scene object " + identity.name + " has no valid sceneId yet."); } } } }
internal static bool IsPrefab(ProBuilderMesh mesh) { return(PrefabUtility.GetPrefabAssetType(mesh.gameObject) != PrefabAssetType.NotAPrefab); }
void Set_Inspector() { GUI.backgroundColor = new Color(1.0f, 1.0f, 0.5f, 1.0f); serializedObject.Update(); EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.HelpBox("Static Track settings", MessageType.None, true); EditorGUILayout.Space(); EditorGUILayout.Slider(MassProp, 1.0f, 100.0f, "Mass"); EditorGUILayout.Slider(Radius_OffsetProp, -0.5f, 0.5f, "Radius Offset"); EditorGUILayout.Slider(Anti_Stroboscopic_MinProp, 0.0f, 1.0f, "Anti Stroboscopic Min"); EditorGUILayout.Slider(Anti_Stroboscopic_MaxProp, 0.0f, 1.0f, "Anti Stroboscopic Max"); EditorGUILayout.Space(); // Check the Prefab Mode. if (PrefabUtility.IsAnyPrefabInstanceRoot(thisTransform.gameObject)) { GUI.backgroundColor = new Color(1.0f, 0.5f, 0.5f, 1.0f); EditorGUILayout.HelpBox("We need to unpack this prefab to equip the tank with Ststic Track.", MessageType.Warning, true); if (GUILayout.Button("Unpack Prefab", GUILayout.Width(200))) { PrefabUtility.UnpackPrefabInstance(thisTransform.gameObject, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction); } return; } if (GUILayout.Button("Set Automatically", GUILayout.Width(200))) { Set_Reference_Wheels_Automatically(); Set_Other_Components_Automatically(); Update_Scripts_Values(); } Reference_LProp.objectReferenceValue = EditorGUILayout.ObjectField("Left Reference Wheel", Reference_LProp.objectReferenceValue, typeof(Transform), true); Reference_RProp.objectReferenceValue = EditorGUILayout.ObjectField("Right Reference Wheel", Reference_RProp.objectReferenceValue, typeof(Transform), true); EditorGUILayout.Space(); if (Reference_LProp.objectReferenceValue != null) { Reference_Name_LProp.stringValue = Reference_LProp.objectReferenceValue.name; Transform tempTransform = Reference_LProp.objectReferenceValue as Transform; if (tempTransform.parent) { Reference_Parent_Name_LProp.stringValue = tempTransform.parent.name; } } else { string tempName = Reference_Name_LProp.stringValue; string tempParentName = Reference_Parent_Name_LProp.stringValue; if (string.IsNullOrEmpty(tempName) == false && string.IsNullOrEmpty(tempParentName) == false) { Reference_LProp.objectReferenceValue = thisTransform.parent.Find(tempParentName + "/" + tempName); } } if (Reference_RProp.objectReferenceValue != null) { Reference_Name_RProp.stringValue = Reference_RProp.objectReferenceValue.name; Transform tempTransform = Reference_RProp.objectReferenceValue as Transform; if (tempTransform.parent) { Reference_Parent_Name_RProp.stringValue = tempTransform.parent.name; } } else { string tempName = Reference_Name_RProp.stringValue; string tempParentName = Reference_Parent_Name_RProp.stringValue; if (string.IsNullOrEmpty(tempName) == false && string.IsNullOrEmpty(tempParentName) == false) { Reference_RProp.objectReferenceValue = thisTransform.parent.Find(tempParentName + "/" + tempName); } } EditorGUILayout.Space(); GUI.backgroundColor = new Color(0.7f, 0.7f, 0.7f, 1.0f); Reference_Parent_Name_LProp.stringValue = EditorGUILayout.TextField("Left Parent Name", Reference_Parent_Name_LProp.stringValue); Reference_Name_LProp.stringValue = EditorGUILayout.TextField("Left Wheel Name", Reference_Name_LProp.stringValue); Reference_Parent_Name_RProp.stringValue = EditorGUILayout.TextField("Right Parent Name", Reference_Parent_Name_RProp.stringValue); Reference_Name_RProp.stringValue = EditorGUILayout.TextField("Right Wheel Name", Reference_Name_RProp.stringValue); GUI.backgroundColor = new Color(1.0f, 1.0f, 0.5f, 1.0f); EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button("Set Types with RoadWheels", GUILayout.Width(200))) { Set_Types_With_RoadWheels(RoadWheel_Effective_RangeProp.floatValue); } EditorGUI.indentLevel++; EditorGUILayout.Slider(RoadWheel_Effective_RangeProp, 0.01f, 2.0f, "Effective Range"); EditorGUI.indentLevel--; EditorGUILayout.Space(); if (GUILayout.Button("Set Types with SwingBalls", GUILayout.Width(200))) { Set_Types_With_SwingBalls(SwingBall_Effective_RangeProp.floatValue); } EditorGUI.indentLevel++; EditorGUILayout.Slider(SwingBall_Effective_RangeProp, 0.01f, 1.0f, "Effective Range"); EditorGUI.indentLevel--; EditorGUILayout.Space(); if (GUILayout.Button("Make Upper Pieces 'Static'", GUILayout.Width(200))) { Make_Upper_Pieces_Static(); } EditorGUILayout.Space(); if (GUILayout.Button("Make All Pieces 'Static'", GUILayout.Width(200))) { Make_All_Pieces_Static(); } EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.HelpBox("Shadow Mesh settings", MessageType.None, true); EditorGUILayout.Space(); Track_L_Shadow_MeshProp.objectReferenceValue = EditorGUILayout.ObjectField("Shadow Mesh of Left", Track_L_Shadow_MeshProp.objectReferenceValue, typeof(Mesh), false); Track_R_Shadow_MeshProp.objectReferenceValue = EditorGUILayout.ObjectField("Shadow Mesh of Right", Track_R_Shadow_MeshProp.objectReferenceValue, typeof(Mesh), false); EditorGUILayout.Space(); if (GUILayout.Button("Update Shadow Mesh", GUILayout.Width(200))) { Update_ShadowMesh(); } EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.HelpBox("Replace BoxColliders with CapsuleColliders.", MessageType.None, true); if (GUILayout.Button("Replace Colliders B to C", GUILayout.Width(200))) { Replace_Colliders_Box_With_Capsules(); } EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.HelpBox("Replace CapsuleColliders with BoxColliders.", MessageType.None, true); if (GUILayout.Button("Replace Colliders C to B", GUILayout.Width(200))) { Replace_Colliders_Capsules_With_Box(); } GUI.backgroundColor = new Color(0.5f, 0.5f, 1.0f, 1.0f); EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.HelpBox("Update the scripts in the pieces.", MessageType.None, true); if (GUILayout.Button("Update the scripts", GUILayout.Width(200))) { Update_Scripts_Values(); } EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUI.changed) { Has_ChangedProp.boolValue = !Has_ChangedProp.boolValue; } serializedObject.ApplyModifiedProperties(); }
/// <summary> /// Returns true if this object is a prefab instanced in the scene. /// </summary> /// <param name="go"></param> /// <returns></returns> internal static bool IsPrefabInstance(GameObject go) { var status = PrefabUtility.GetPrefabInstanceStatus(go); return(status == PrefabInstanceStatus.Connected || status == PrefabInstanceStatus.Disconnected); }
public static void ReadLevelFromFile(string filePath, TileContainer tileContainer) { ClearScene(); string level = File.ReadAllText(filePath); int width = tileContainer.width; int height = tileContainer.height; int direction = 1; switch (tileContainer.readMethod) { case 0: { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int index = tileContainer.tileSymbol.IndexOf(level[x + y * width].ToString()); string tag = tileContainer.tileTag[index]; GameObject tile = AssetDatabase.LoadAssetAtPath("Assets/LevelGenerator/Tiles/" + tag + ".prefab", typeof(GameObject)) as GameObject; tile = PrefabUtility.InstantiatePrefab(tile) as GameObject; tile.transform.position = new Vector2(x, y); LoadBackgroundElement(tile, x, y); } } return; } case 1: { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int index = tileContainer.tileSymbol.IndexOf(level[y + x * height].ToString()); string tag = tileContainer.tileTag[index]; GameObject tile = AssetDatabase.LoadAssetAtPath("Assets/LevelGenerator/Tiles/" + tag + ".prefab", typeof(GameObject)) as GameObject; tile = PrefabUtility.InstantiatePrefab(tile) as GameObject; tile.transform.position = new Vector2(x, y); LoadBackgroundElement(tile, x, y); } } return; } case 2: { for (int x = 0; x < width; x++) { if (direction == 1) { for (int y = 0; y < height; y++) { int index = tileContainer.tileSymbol.IndexOf(level[y + x * height].ToString()); string tag = tileContainer.tileTag[index]; GameObject tile = AssetDatabase.LoadAssetAtPath("Assets/LevelGenerator/Tiles/" + tag + ".prefab", typeof(GameObject)) as GameObject; tile = PrefabUtility.InstantiatePrefab(tile) as GameObject; tile.transform.position = new Vector2(x, y); LoadBackgroundElement(tile, x, y); } } else { for (int y = 0; y < height; y++) { int index = tileContainer.tileSymbol.IndexOf(level[y + x * height].ToString()); string tag = tileContainer.tileTag[index]; GameObject tile = AssetDatabase.LoadAssetAtPath("Assets/LevelGenerator/Tiles/" + tag + ".prefab", typeof(GameObject)) as GameObject; tile = PrefabUtility.InstantiatePrefab(tile) as GameObject; tile.transform.position = new Vector2(x, height - 1 - y); LoadBackgroundElement(tile, x, height - 1 - y); } } direction = -direction; } return; } } }
/** * Returns true if this object is a prefab in the Project view. */ internal static bool IsPrefabAsset(GameObject go) { return(PrefabUtility.IsPartOfPrefabAsset(go)); }
/// <summary> /// All widgets have depth, color and make pixel-perfect options /// </summary> protected void DrawCommonProperties() { #if UNITY_3_4 PrefabType type = EditorUtility.GetPrefabType(mWidget.gameObject); #else PrefabType type = PrefabUtility.GetPrefabType(mWidget.gameObject); #endif NGUIEditorTools.DrawSeparator(); // Depth navigation if (type != PrefabType.Prefab) { GUILayout.BeginHorizontal(); { EditorGUILayout.PrefixLabel("Depth"); int depth = mWidget.depth; if (GUILayout.Button("Back")) { --depth; } depth = EditorGUILayout.IntField(depth, GUILayout.Width(40f)); if (GUILayout.Button("Forward")) { ++depth; } if (mWidget.depth != depth) { NGUIEditorTools.RegisterUndo("Depth Change", mWidget); mWidget.depth = depth; } } GUILayout.EndHorizontal(); } Color color = EditorGUILayout.ColorField("Color Tint", mWidget.color); if (mWidget.color != color) { NGUIEditorTools.RegisterUndo("Color Change", mWidget); mWidget.color = color; } // Depth navigation if (type != PrefabType.Prefab) { GUILayout.BeginHorizontal(); { EditorGUILayout.PrefixLabel("Correction"); if (GUILayout.Button("Make Pixel-Perfect")) { NGUIEditorTools.RegisterUndo("Make Pixel-Perfect", mWidget.transform); mWidget.MakePixelPerfect(); } } GUILayout.EndHorizontal(); } UIWidget.Pivot pivot = (UIWidget.Pivot)EditorGUILayout.EnumPopup("Pivot", mWidget.pivot); if (mWidget.pivot != pivot) { NGUIEditorTools.RegisterUndo("Pivot Change", mWidget); mWidget.pivot = pivot; } if (mAllowPreview && mWidget.mainTexture != null) { GUILayout.BeginHorizontal(); { UISettings.texturePreview = EditorGUILayout.Toggle("Preview", UISettings.texturePreview, GUILayout.Width(100f)); /*if (UISettings.texturePreview) * { * if (mUseShader != EditorGUILayout.Toggle("Use Shader", mUseShader)) * { * mUseShader = !mUseShader; * * if (mUseShader) * { * // TODO: Remove this when Unity fixes the bug with DrawPreviewTexture not being affected by BeginGroup * Debug.LogWarning("There is a bug in Unity that prevents the texture from getting clipped properly.\n" + * "Until it's fixed by Unity, your texture may spill onto the rest of the Unity's GUI while using this mode."); * } * } * }*/ } GUILayout.EndHorizontal(); // Draw the texture last if (UISettings.texturePreview) { OnDrawTexture(); } } }
protected void DrawSpriteEditorGUI(tk2dBaseSprite sprite) { Event ev = Event.current; tk2dSpriteGuiUtility.SpriteSelector(sprite.Collection, sprite.spriteId, spriteChangedCallbackInstance, null); if (sprite.Collection != null && tk2dPreferences.inst.displayTextureThumbs) { tk2dSpriteDefinition def = sprite.GetCurrentSpriteDef(); if (sprite.Collection.version < 1 || def.texelSize == Vector2.zero) { string message = ""; message = "No thumbnail data."; if (sprite.Collection.version < 1) { message += "\nPlease rebuild Sprite Collection."; } tk2dGuiUtility.InfoBox(message, tk2dGuiUtility.WarningLevel.Info); } else { GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(" "); Vector2 texSize = thumbnailCache.GetSpriteSizePixels(def); float w = texSize.x; float h = texSize.y; float maxSize = 128.0f; if (w > maxSize) { h = h / w * maxSize; w = maxSize; } if (h > maxSize) { w = w / h * maxSize; h = maxSize; } Rect r = GUILayoutUtility.GetRect(w, h, GUILayout.ExpandWidth(false)); tk2dGrid.Draw(r); thumbnailCache.DrawSpriteTexture(r, def); GUILayout.EndHorizontal(); r = GUILayoutUtility.GetLastRect(); if (ev.type == EventType.MouseDown && ev.button == 0 && r.Contains(ev.mousePosition)) { tk2dSpriteGuiUtility.SpriteSelectorPopup(sprite.Collection, sprite.spriteId, spriteChangedCallbackInstance, null); } } sprite.color = EditorGUILayout.ColorField("Color", sprite.color); Vector3 newScale = EditorGUILayout.Vector3Field("Scale", sprite.scale); if (newScale != sprite.scale) { sprite.scale = newScale; sprite.EditMode__CreateCollider(); } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("HFlip")) { Vector3 s = sprite.scale; s.x *= -1.0f; sprite.scale = s; GUI.changed = true; } if (GUILayout.Button("VFlip")) { Vector3 s = sprite.scale; s.y *= -1.0f; sprite.scale = s; GUI.changed = true; } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button(new GUIContent("Reset Scale", "Set scale to 1"))) { Vector3 s = sprite.scale; s.x = Mathf.Sign(s.x); s.y = Mathf.Sign(s.y); s.z = Mathf.Sign(s.z); sprite.scale = s; GUI.changed = true; } if (GUILayout.Button(new GUIContent("Bake Scale", "Transfer scale from transform.scale -> sprite"))) { tk2dScaleUtility.Bake(sprite.transform); GUI.changed = true; } GUIContent pixelPerfectButton = new GUIContent("1:1", "Make Pixel Perfect"); if (GUILayout.Button(pixelPerfectButton)) { if (tk2dPixelPerfectHelper.inst) { tk2dPixelPerfectHelper.inst.Setup(); } sprite.MakePixelPerfect(); GUI.changed = true; } sprite.pixelPerfect = GUILayout.Toggle(sprite.pixelPerfect, new GUIContent("Always", "Always keep pixel perfect"), GUILayout.Width(60.0f)); EditorGUILayout.EndHorizontal(); } else { EditorGUILayout.IntSlider("Need a collection bound", 0, 0, 1); } bool needUpdatePrefabs = false; if (GUI.changed) { EditorUtility.SetDirty(sprite); #if !(UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4) if (PrefabUtility.GetPrefabType(sprite) == PrefabType.Prefab) { needUpdatePrefabs = true; } #endif } // This is a prefab, and changes need to be propagated. This isn't supported in Unity 3.4 if (needUpdatePrefabs) { #if !(UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4) // Rebuild prefab instances tk2dBaseSprite[] allSprites = Resources.FindObjectsOfTypeAll(sprite.GetType()) as tk2dBaseSprite[]; foreach (var spr in allSprites) { if (PrefabUtility.GetPrefabType(spr) == PrefabType.PrefabInstance && PrefabUtility.GetPrefabParent(spr.gameObject) == sprite.gameObject) { // Reset all prefab states var propMod = PrefabUtility.GetPropertyModifications(spr); PrefabUtility.ResetToPrefabState(spr); PrefabUtility.SetPropertyModifications(spr, propMod); spr.ForceBuild(); } } #endif } }
private void Save() { string s = string.Format("{0}/", EditorUtility.OpenFolderPanel("选择导出路径", savePath, "")); if (s.Contains("Assets")) { savePath = s.Substring(s.LastIndexOf("Assets")); var o = new GameObject(go.name); var gpuAnim = o.AddComponent <GPUAnimation> (); var cfg = ScriptableObject.CreateInstance(typeof(GPUAnimCfg)) as GPUAnimCfg; o.name = go.name; Material mat = null; Texture2D combinedTex = null; if (type == bakeType.SkeletonAnim) { mat = new Material(Shader.Find("Unlit/GPUAnimSkinning")); mat.name = go.name + "_skinMat"; combinedTex = CreateSkeletonTexture(); combinedTex.name = go.name + "_skinTex"; // savePath += "/" + o.name + "_Skeleton" + "/"; } else if (type == bakeType.VertexAnim) { mat = new Material(Shader.Find("Unlit/GPUAnimVertex")); mat.name = go.name + "_vertMat"; combinedTex = CreateVertexTexture(); combinedTex.name = go.name + "_vertTex"; // savePath += "/" + o.name + "_Vertex" + "/"; } mat.enableInstancing = true; foreach (var info in animDatas) { info.startFrame += 1; //部分动画闪烁,去掉头尾就可以吃了... info.frameCount -= 2; //...Orz cfg.AnimClips.Add(info as AnimClipInfo); } if (!AssetDatabase.IsValidFolder(savePath + o.name)) { AssetDatabase.CreateFolder(savePath.TrimEnd('/'), o.name); } savePath += o.name + "/"; AssetDatabase.CreateAsset(cfg, Path.Combine(savePath, o.name + "_animInfo.asset")); AssetDatabase.CreateAsset(combinedTex, Path.Combine(savePath, combinedTex.name + ".asset")); // SaveAsPng (s, combinedTex); mat.SetTexture("_MainTex", material.GetTexture("_MainTex")); mat.SetTexture("_AnimMap", combinedTex); AssetDatabase.CreateAsset(mat, Path.Combine(savePath, mat.name + ".mat")); gpuAnim.animCfg = cfg; gpuAnim.GetComponent <MeshFilter> ().sharedMesh = mesh; gpuAnim.GetComponent <Renderer> ().sharedMaterial = mat; if (type == bakeType.SkeletonAnim) { PrefabUtility.CreatePrefab(Path.Combine(savePath, o.name + "_skeletonPrefab.prefab"), o); } else if (type == bakeType.VertexAnim) { PrefabUtility.CreatePrefab(Path.Combine(savePath, o.name + "_vertexPrefab.prefab"), o); } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); DestroyImmediate(o); } }
// Called when updating this editor window void OnGUI() { windowScrollPosition = EditorGUILayout.BeginScrollView(windowScrollPosition); Catalog = (LevelEditorCatalog)EditorGUILayout.ObjectField("Object Catalog", Catalog, typeof(LevelEditorCatalog), false); if (!CatalogLoaded) { EditorGUILayout.HelpBox("Load a catalog (TileEditorCatalog) to access all functionality.\nTo create a catalog, use the Create menu in the Assets folder and look for Level Editor/Level Editor Catalog.", MessageType.Warning); } using (new EditorGUILayout.HorizontalScope()) { GUILayout.Label("Object Placement", EditorStyles.boldLabel, GUILayout.Width(position.width - 65)); if (GUILayout.Button("Reload")) { CheckCatalog(); } } using (new EditorGUI.DisabledGroupScope(!CatalogLoaded)) { using (new EditorGUILayout.HorizontalScope()) { float buttonWidth = (position.width - 3f) * 0.2f - 4f; if (GUILayout.Toggle(PlacingMode == PlacingModes.Off, placingModes[0], "button", GUILayout.Width(buttonWidth))) { PlacingMode = PlacingModes.Off; arcPlacingStarted = wallPlacingStarted = false; RemoveGhosts(); } if (GUILayout.Toggle(PlacingMode == PlacingModes.Single, placingModes[1], "button", GUILayout.Width(buttonWidth))) { PlacingMode = PlacingModes.Single; arcPlacingStarted = wallPlacingStarted = false; } using (new EditorGUI.DisabledGroupScope(!CatalogLoaded || !inventory[selectedItem].isArc)) { if (GUILayout.Toggle(PlacingMode == PlacingModes.Arc, placingModes[2], "button", GUILayout.Width(buttonWidth))) { PlacingMode = PlacingModes.Arc; wallPlacingStarted = false; } if (GUILayout.Toggle(PlacingMode == PlacingModes.Wall, placingModes[3], "button", GUILayout.Width(buttonWidth))) { PlacingMode = PlacingModes.Wall; arcPlacingStarted = false; } if (GUILayout.Toggle(PlacingMode == PlacingModes.Ring, placingModes[4], "button", GUILayout.Width(buttonWidth))) { PlacingMode = PlacingModes.Ring; arcPlacingStarted = wallPlacingStarted = false; } } } //placingMode = GUILayout.SelectionGrid(placingMode, placingModes, placingModes.Length, "button"); if (PlacingMode != PlacingModes.Off) { Tools.current = Tool.None; } else if (Tools.current == Tool.None) { Tools.current = Tool.Move; } } #region Rotation controls EditorGUILayout.BeginHorizontal(); using (new EditorGUI.DisabledGroupScope(!CatalogLoaded)) { autoRotateEnabled = EditorGUILayout.Toggle("Auto rotate", autoRotateEnabled); } using (new EditorGUI.DisabledGroupScope(true)) GUILayout.Button(new GUIContent("↺", "Rotate 90° CCW"), GUILayout.Width(20)); if (GUILayout.Button("Rotate Selection", GUILayout.ExpandWidth(false))) { RotateSelection(); } using (new EditorGUI.DisabledGroupScope(true)) GUILayout.Button(new GUIContent("↻", "Rotate 90° CW"), GUILayout.Width(20)); EditorGUILayout.EndHorizontal(); #endregion Rotation controls #region Radial and angular snapping controls using (new EditorGUILayout.HorizontalScope()) { using (new EditorGUI.DisabledGroupScope(!CatalogLoaded)) { GUILayout.Label("Snapping:", GUILayout.Width(146)); } using (new EditorGUILayout.HorizontalScope()) { using (new EditorGUI.DisabledGroupScope(!CatalogLoaded)) { var snapHS = new EditorGUILayout.HorizontalScope(GUILayout.MaxWidth(57)); radialSnapEnabled = GUI.Toggle(snapHS.rect, radialSnapEnabled, "", "button"); GUILayout.Label(" Radial"); snapHS.Dispose(); snapHS = new EditorGUILayout.HorizontalScope(GUILayout.MaxWidth(57)); angularSnapEnabled = GUI.Toggle(snapHS.rect, angularSnapEnabled, "", "button"); GUILayout.Label(" Angular"); snapHS.Dispose(); GUILayout.FlexibleSpace(); drawGuides = EditorGUILayout.ToggleLeft("Guides", drawGuides, GUILayout.Width(60)); } } } using (new EditorGUI.DisabledGroupScope(!CatalogLoaded)) { using (new EditorGUILayout.HorizontalScope()) { GUILayout.Label("Angular Divisions", GUILayout.Width(146)); using (new EditorGUILayout.HorizontalScope()) { selectedAngularDensity = EditorGUILayout.IntPopup(selectedAngularDensity, new string[] { "Auto", "6", "12", "24", "48", "96", "192", "384", "768", "Custom..." }, new int[] { 0, 6, 12, 24, 48, 96, 192, 384, 768, -1 }); if (selectedAngularDensity == -1) { customAngularDensity = EditorGUILayout.IntField(customAngularDensity); } } } using (new EditorGUILayout.HorizontalScope()) { GUILayout.Label("Radial Thickness", GUILayout.Width(146)); using (new EditorGUILayout.HorizontalScope()) { selectedRadialThickness = EditorGUILayout.Popup(selectedRadialThickness, new string[] { "0.25 m", "50 m", "0.75 m", "1 m", "2 m", "Custom..." }); switch (selectedRadialThickness) { case 0: radialThickness = 0.25f; break; case 1: radialThickness = 0.5f; break; case 2: radialThickness = 0.75f; break; case 3: radialThickness = 1f; break; case 4: radialThickness = 2f; break; case 5: radialThickness = EditorGUILayout.Slider(radialThickness, 0.1f, 10); break; default: break; } } } } #endregion Radial and angular snapping controls EditorGUILayout.Space(); #region Catalog if (CatalogLoaded) { Color defColor = GUI.backgroundColor; Color highlight = EditorStyles.label.focused.textColor.Lighter().Lighter().Lighter().Lighter(); // Prefab selector scroll view using (var scrollView = new EditorGUILayout.ScrollViewScope(itemSelectorScrollPosition)) { GUI.backgroundColor = Color.gray; using (var v = new EditorGUILayout.VerticalScope()) { GUI.Box(v.rect, ""); // Here we populate the list view ... int n = 0; while (n < inventory.Count) { // ... row by row ... using (var H = new EditorGUILayout.HorizontalScope()) { int w = 0; do { // ... element by element using (var h = new EditorGUILayout.HorizontalScope("button", GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false), GUILayout.MaxWidth(catalogIconSize), GUILayout.MaxHeight(catalogIconSize), GUILayout.Width(catalogIconSize), GUILayout.Height(catalogIconSize))) { // A checkbox disguised as a button with the functionality of a radio button Texture2D tex = Catalog[n].GetIcon(); string displayName = Catalog[n].displayName; GUIContent content = new GUIContent(tex, displayName); // The toggle with an image if (n == selectedItem) { GUI.backgroundColor = highlight; } if (GUI.Toggle(h.rect, n == selectedItem ? true : false, content, "button")) { if (selectedItem != n) { if (ghost != null) { DestroyImmediate(ghost.gameObject); } selectedItem = n; if (!inventory[selectedItem].isArc && PlacingMode != PlacingModes.Off) { PlacingMode = PlacingModes.Single; } } } GUI.backgroundColor = Color.gray; // and some text over it GUIStyle style = new GUIStyle(EditorStyles.boldLabel); style.normal.textColor = n == selectedItem ? highlight : Color.white; style.wordWrap = true; GUILayout.Label(displayName, style); } w += catalogIconSize; n++; } while (n < inventory.Count && w < (position.width - catalogIconSize)); } } itemSelectorScrollPosition = scrollView.scrollPosition; } GUI.backgroundColor = defColor; } } #endregion Catalog GUILayout.Label("Level Parameters", EditorStyles.boldLabel); using (new EditorGUI.DisabledGroupScope(!CatalogLoaded)) { LookForBasicObjects(); using (new EditorGUILayout.HorizontalScope()) { levelObjectsFoldoutState = EditorGUILayout.Foldout(levelObjectsFoldoutState, "Basic objects", true); if (GUILayout.Button("Prepare Level", GUILayout.Width(100))) { PrepareLevel(); } } if (levelObjectsFoldoutState) { player = (GameObject)EditorGUILayout.ObjectField("Player", player, typeof(GameObject), true); if (player != null) { if (PrefabUtility.GetPrefabType(player) == PrefabType.Prefab) { player = null; } } camera = (Camera)EditorGUILayout.ObjectField("Camera", camera, typeof(Camera), true); if (camera != null) { if (PrefabUtility.GetPrefabType(camera) == PrefabType.Prefab) { camera = null; } } forceField = (GameObject)EditorGUILayout.ObjectField("Force Field", forceField, typeof(GameObject), true); if (forceField != null) { if (PrefabUtility.GetPrefabType(forceField) == PrefabType.Prefab) { forceField = null; } } lights = (GameObject)EditorGUILayout.ObjectField("Spotlights", lights, typeof(GameObject), true); if (lights != null) { if (PrefabUtility.GetPrefabType(lights) == PrefabType.Prefab) { lights = null; } } } } EditorGUILayout.EndScrollView(); }
private bool CreateRandomObjectAtLoc(Vector2 loc, float finalMinDistSqrd, out bool objectPlaced, WeightedArray weightedObjects, ObjectOptions[] objectOptions, bool preview) { objectPlaced = false; if (InBounds(loc)) { bool toCloseToProcess = true; // Don't do InNeighbourhood for clumping algorithm if (finalMinDistSqrd <= 0 || (!InNeighbourhood(loc, finalMinDistSqrd, out toCloseToProcess) && !InInnerBounds(loc))) { RaycastHit hit; if (CastRay(loc, out hit)) { int index = weightedObjects.GetRandomObjectIndex(); ObjectOptions options = objectOptions[index]; float dotResult = Vector3.Dot(hit.normal, Vector3.up); if (dotResult >= options.MinDot && dotResult <= options.MaxDot) { Vector3 pos = hit.point; Quaternion rot; Vector3 scale; ApplySettingsToObject(options, hit.normal, ref pos, out rot, out scale); GameObject newObject = weightedObjects.GetGameObject(index); if (newObject != null) { if (_activeData.SphereCollisionCheck || _activeData.BoxCollisionCheck) { Bounds bounds; if (GetBounds(newObject, _activeData.BoundsMode, pos, rot, scale, out bounds)) { if (ModeData.Mode == DistributionMode.Surface) { ModeData.Surface.gameObject.SetActive(false); } bool hasOverlap = true; LayerMask correctedMask = InternalEditorUtility.ConcatenatedLayersMaskToLayerMask(_activeData.OverlapLayerMask); if (_activeData.SphereCollisionCheck) { hasOverlap = CheckSphereOverlap(bounds, correctedMask); } if (_activeData.BoxCollisionCheck && hasOverlap) { hasOverlap = CheckBoxOverlap(bounds, rot, correctedMask); } if (ModeData.Mode == DistributionMode.Surface) { ModeData.Surface.gameObject.SetActive(true); } if (hasOverlap) { return(!toCloseToProcess); } } } } else { return(!toCloseToProcess); } objectPlaced = true; GameObject obj = (GameObject)PrefabUtility.InstantiatePrefab(newObject); obj.transform.position = pos; obj.transform.rotation = rot; obj.transform.localScale = scale; // When not doing this the colliders aren't properly initialized and OverlapXXX won't work obj.SetActive(false); obj.SetActive(true); obj.transform.parent = options.Parent; EditorData.PlacedObjects[_activeLevel].Add(obj); if (_currNestingLevel < _maxNestingLevel) { PoissonPlacer placer = obj.GetComponent <PoissonPlacer>(); if (placer != null && placer.enabled) { PoissonHelper helper = new PoissonHelper(placer); helper.Init(); bool isValidSurface, preValid, currValid, postValid; int highestValid; helper.LoadDataHolder(); helper.ValidateSettings(false, out isValidSurface, out preValid, out currValid, out postValid, out highestValid); placer.EditorData.LastFrameValid = isValidSurface && preValid && currValid && postValid; if (highestValid >= 0) { Random.State randState = Random.state; helper.DistributePoisson(0, highestValid, preview, _currNestingLevel + 1, _maxNestingLevel); Random.state = randState; } helper.StoreDataHolder(); } } } } } return(!toCloseToProcess || objectPlaced); } return(false); }
/// <summary> /// [EDITOR] Save a CharacterViewer as a prefab in a selected path and automatically generate its materials. /// </summary> /// <param name="character">CharacterViewer to be saved as prefab.</param> /// <param name="path">The path must be in Assets directory.</param> /// <returns>'true' on succes, otherwise returns 'false'.</returns> public static bool SaveCharacterToPrefab(CharacterViewer sourceCharacter, string path) { #if UNITY_EDITOR try { List <Material> materials = new List <Material>(); //..get all character's materials foreach (SlotCategory c in Enum.GetValues(typeof(SlotCategory))) { PartSlot slot = sourceCharacter.slots.GetSlot(c); if (slot == null || slot.material == null || materials.Contains(slot.material)) { continue; } slot.material.name = slot.material.name.Replace("CC2D", sourceCharacter.name); materials.Add(slot.material); } //get all character's materials.. string materialfolder = string.Format("{0}/{1}_materials", Path.GetDirectoryName(path), sourceCharacter.name); if (!Directory.Exists(materialfolder)) { Directory.CreateDirectory(materialfolder); AssetDatabase.Refresh(); } foreach (Material m in materials) { string filename = string.Format("{0}/{1}.mat", materialfolder, m.name); AssetDatabase.CreateAsset(m, filename); } AssetDatabase.Refresh(); sourceCharacter.RelinkMaterials(); #if UNITY_2018_3_OR_NEWER if (AssetDatabase.LoadAssetAtPath <CharacterViewer>(path) != null) { GameObject targetgo = PrefabUtility.LoadPrefabContents(path); CharacterViewer targetchara = targetgo.GetComponent <CharacterViewer>(); Transform sourceroot = sourceCharacter.transform.Find("Root"); Transform targetroot = targetchara.transform.Find("Root"); if (targetroot != null) { GameObject.DestroyImmediate(targetroot.gameObject); } if (sourceroot != null) { targetroot = GameObject.Instantiate <Transform>(sourceroot); targetroot.name = "Root"; targetroot.SetParent(targetchara.transform); targetroot.localPosition = Vector3.zero; EditorUtility.CopySerialized(sourceCharacter, targetchara); PrefabUtility.SaveAsPrefabAsset(targetgo, path); PrefabUtility.UnloadPrefabContents(targetgo); } } else { PrefabUtility.SaveAsPrefabAsset(sourceCharacter.gameObject, path); } #else CharacterViewer extcharacter = AssetDatabase.LoadAssetAtPath <CharacterViewer>(path); if (extcharacter != null) { PrefabUtility.ReplacePrefab(sourceCharacter.gameObject, extcharacter); } else { PrefabUtility.CreatePrefab(path, sourceCharacter.gameObject, ReplacePrefabOptions.ConnectToPrefab); } #endif AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); return(true); } catch (Exception e) { Debug.LogError("error on save character to prefab:\n" + e.ToString()); return(false); } #else return(false); #endif }
public void OnGUI() { if (settings == null) { settings = AssetDatabase.LoadAssetAtPath <NestedPrefabCategorySettings>(pathToSetting); if (settings == null) { Debug.LogWarning("You need to create the NestedPrefabsCategories to be able to register your nested prefab"); settings = CreateInstance <NestedPrefabCategorySettings>(); AssetDatabase.CreateAsset(settings, pathToSetting); AssetDatabase.SaveAssets(); } } if (onFirstOnGUI) { GetModelType(); onFirstOnGUI = false; } EditorGUILayout.BeginVertical(); EditorGUILayout.Space(); GUILayout.Label("Catégorie :"); EditorGUI.indentLevel++; if (EditorGUILayout.Toggle("Shop", selectedNestedPrefabCategory.categoryNameNested == NestedPrefabCategoryName.Shop)) { if (selectedNestedPrefabCategory.categoryNameNested != NestedPrefabCategoryName.Shop) { selectedNestedPrefabCategory = settings.shopNestPrefab; GetModelType(); } } if (EditorGUILayout.Toggle("Mall", selectedNestedPrefabCategory.categoryNameNested == NestedPrefabCategoryName.Mall)) { if (selectedNestedPrefabCategory.categoryNameNested != NestedPrefabCategoryName.Mall) { selectedNestedPrefabCategory = settings.mallNestPrefab; GetModelType(); } } if (EditorGUILayout.Toggle("Apartment", selectedNestedPrefabCategory.categoryNameNested == NestedPrefabCategoryName.Apartment)) { if (selectedNestedPrefabCategory.categoryNameNested != NestedPrefabCategoryName.Apartment) { selectedNestedPrefabCategory = settings.apartmentNestPrefab; GetModelType(); } } EditorGUI.indentLevel--; EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.EndVertical(); if (selectedNestedPrefabCategory.categoryNameNested == NestedPrefabCategoryName.Shop) { GUILayout.Label("Wealth :"); EditorGUI.indentLevel++; if (EditorGUILayout.Toggle("Poor", selectedWealthLevelShop == WealthLevelShop.Poor)) { if (selectedWealthLevelShop != WealthLevelShop.Poor) { selectedWealthLevelShop = WealthLevelShop.Poor; GetModelType(); } } if (EditorGUILayout.Toggle("Normal", selectedWealthLevelShop == WealthLevelShop.Normal)) { if (selectedWealthLevelShop != WealthLevelShop.Normal) { selectedWealthLevelShop = WealthLevelShop.Normal; GetModelType(); } } if (EditorGUILayout.Toggle("Rich", selectedWealthLevelShop == WealthLevelShop.Rich)) { if (selectedWealthLevelShop != WealthLevelShop.Rich) { selectedWealthLevelShop = WealthLevelShop.Rich; GetModelType(); } } EditorGUI.indentLevel--; EditorGUILayout.Space(); GUILayout.Label("Size :"); EditorGUI.indentLevel++; if (EditorGUILayout.Toggle("Small", selectedSizeShop == SizeShop.Small)) { if (selectedSizeShop != SizeShop.Small) { selectedSizeShop = SizeShop.Small; GetModelType(); } } if (EditorGUILayout.Toggle("Big", selectedSizeShop == SizeShop.Big)) { if (selectedSizeShop != SizeShop.Big) { selectedSizeShop = SizeShop.Big; GetModelType(); } } EditorGUI.indentLevel--; EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.Space(); } else if (selectedNestedPrefabCategory.categoryNameNested == NestedPrefabCategoryName.Apartment) { GUILayout.Label("Size :"); EditorGUI.indentLevel++; if (EditorGUILayout.Toggle("Tiny", seletectedSizeApartment == SizeApartment.Tiny)) { if (seletectedSizeApartment != SizeApartment.Tiny) { seletectedSizeApartment = SizeApartment.Tiny; GetModelType(); } } if (EditorGUILayout.Toggle("Small", seletectedSizeApartment == SizeApartment.Small)) { if (seletectedSizeApartment != SizeApartment.Small) { seletectedSizeApartment = SizeApartment.Small; GetModelType(); } } if (EditorGUILayout.Toggle("Normal", seletectedSizeApartment == SizeApartment.Medium)) { if (seletectedSizeApartment != SizeApartment.Medium) { seletectedSizeApartment = SizeApartment.Medium; GetModelType(); } } if (EditorGUILayout.Toggle("Big", seletectedSizeApartment == SizeApartment.Big)) { if (seletectedSizeApartment != SizeApartment.Big) { seletectedSizeApartment = SizeApartment.Big; GetModelType(); } } EditorGUI.indentLevel--; EditorGUILayout.Space(); } if (EditorGUILayout.Toggle("Center", centerNewObject)) { if (!centerNewObject) { centerNewObject = !centerNewObject; } } else { if (centerNewObject) { centerNewObject = !centerNewObject; } } if (settings.shopNestPrefab.categoryNameNested == settings.mallNestPrefab.categoryNameNested && settings.mallNestPrefab.categoryNameNested == settings.apartmentNestPrefab.categoryNameNested && settings.apartmentNestPrefab.categoryNameNested == settings.shopNestPrefab.categoryNameNested) { GUILayout.Label("Please fill correctly NestedPrefabCategorySettings in the Editor Folder"); } else { if (GUILayout.Button("Create prefab") && AskCreatePrefab()) { foreach (Transform child in prefabParent.transform) { RecursivelyRemoveProceduralEntitiesChildren(child.gameObject); } string localPath = selectedNestedPrefabCategory.pathFolder; if (selectedNestedPrefabCategory.categoryNameNested == NestedPrefabCategoryName.Shop) { localPath += selectedWealthLevelShop + "/" + selectedSizeShop + "/"; } else if (selectedNestedPrefabCategory.categoryNameNested == NestedPrefabCategoryName.Apartment) { localPath += seletectedSizeApartment + "/"; } else if (selectedNestedPrefabCategory.categoryNameNested == NestedPrefabCategoryName.Mall) { localPath += "Mall/"; } if (!Directory.Exists(localPath)) { Directory.CreateDirectory(localPath); } localPath += prefabParent.name + ".prefab"; localPath = AssetDatabase.GenerateUniqueAssetPath(localPath); PrefabUtility.SaveAsPrefabAssetAndConnect(prefabParent, localPath, InteractionMode.AutomatedAction); GetModelType(); Debug.Log("Nested prefab created"); } } }
/// <summary> /// Determine if we're dealing with an actual prefab or an instance /// </summary> /// <param name="rMountPoints"></param> /// <returns></returns> private bool IsAddMountPointEnabled(Mount rMount) { PrefabType lType = PrefabUtility.GetPrefabType(rMount); return(lType != PrefabType.Prefab); }