Hello,
I try to write a script that can write in a text file all my structure for a scene.
Example :
[Name:FirstPersonController, Tag:Player]
–[Name:Camera, Tag:Undefined]
[Name:ZombieController, Tag:Zombies]
–[Name:ZombieHead, Tag:Undefined]
–[Name:ZombieArms, Tag:Undefined]
etc …
How can I achieve that ?
using UnityEngine;
using System.Collections;
public class HierarchyWriter : MonoBehaviour
{
private void Start()
{
GameObject[] rootGameObjects = gameObject.scene.GetRootGameObjects();
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
for ( int gameObjectIndex = 0 ; gameObjectIndex < rootGameObjects.Length ; gameObjectIndex++ )
{
AppendGameObjectToString( rootGameObjects[gameObjectIndex], stringBuilder, 0 );
}
WriteIntoFile( stringBuilder.ToString() );
}
private void AppendGameObjectToString( GameObject gameObject, System.Text.StringBuilder stringBuilder, int level )
{
for ( int i = 0 ; i < level ; ++i )
stringBuilder.Append( "--" );
stringBuilder.Append( string.Format("[Name: {0}, Tag: {1}]
", gameObject.name, gameObject.tag ) );
for( int childIndex = 0 ; childIndex < gameObject.transform.childCount ; ++childIndex )
{
AppendGameObjectToString( gameObject.transform.GetChild( childIndex ).gameObject, stringBuilder, level + 1 );
}
}
private void WriteIntoFile( string fileContent )
{
// See
// https://support.unity3d.com/hc/en-us/articles/115000341143-How-do-I-read-and-write-data-from-a-text-file-
Debug.Log( fileContent ) ;
}
}
Thanks, it work like a charm 