Script Converting for swaping prefabs
So, I am trying to use AssetBundles stuff, so I have a terrain, assign to its trees regular prefabs of trees to use, and in a sence dress up the scene/terrain how I want it.
I need to pull off the trees from the terrain data, and I have a script that does that ok, in a sence makes a seperate set of gameobjects to store the original prefab.
But I need to Swap the prefabs with other prefabs to not use regular resources/assets but the assetbundle versions of those prefabs.
So in the project, I have 2 Prefabs for each thing in asset bundles, like my trees, I have 1 Prefab that is the actual tree prefab, and a second prefab that only holds needs scripts and a assetbundle loader to load the same prefab.
So if my real tree is say, _AssetBundles/Trees/tree1.prefab
, that is the tree in the terrain then I have a Resources/AssetLoader/Trees/tree1.prefab
I want the script to not just pop them on a gameobject but to replace the prefabs themselfs with the same prefab name just in a diffrent location, ie the Resources/AssetLoader/PreFabName that matches the original prefab in the terrain/trees
My Current script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
// Replaces Unity terrain trees with prefab GameObject.
// http://answers.unity3d.com/questions/723266/converting-all-terrain-trees-to-gameobjects.html
[ExecuteInEditMode]
public class TreeReplacerS : EditorWindow
{
[Header("References")]
public Terrain _terrain;
//============================================
[MenuItem("Window/My/TreeReplacer")]
static void Init()
{
TreeReplacerS window = (TreeReplacerS)GetWindow(typeof(TreeReplacerS));
}
void OnGUI()
{
_terrain = (Terrain)EditorGUILayout.ObjectField(_terrain, typeof(Terrain), true);
if (GUILayout.Button("Convert to objects"))
{
Convert();
}
if (GUILayout.Button("Clear generated trees"))
{
Clear();
}
}
//============================================
public void Convert()
{
TerrainData data = _terrain.terrainData;
float width = data.size.x;
float height = data.size.z;
float y = data.size.y;
// Create parent
GameObject parent = GameObject.Find("TREES_GENERATED");
if (parent == null)
{
parent = new GameObject("TREES_GENERATED");
}
// Create trees
foreach (TreeInstance tree in data.treeInstances)
{
if (tree.prototypeIndex >= data.treePrototypes.Length)
continue;
var _tree = data.treePrototypes[tree.prototypeIndex].prefab;
Vector3 position = new Vector3(
tree.position.x * width,
tree.position.y * y,
tree.position.z * height) + _terrain.transform.position;
Vector3 scale = new Vector3(tree.widthScale, tree.heightScale, tree.widthScale);
GameObject go = Instantiate(_tree, position, Quaternion.Euler(0f, Mathf.Rad2Deg * tree.rotation, 0f), parent.transform) as GameObject;
go.transform.localScale = scale;
}
}
public void Clear()
{
DestroyImmediate(GameObject.Find("TREES_GENERATED"));
}
}