Unity3d 동적 로드 및 구성 파일 생성

65005 단어
본고는 대부분 전재되었고 저자는 프로필 생성에 관한 작업을 했지만 유감스럽게도position과rotation에 대한 정보는 아직 자동으로 생성되지 않았습니다. 이 예를 실행하는 친구는 위치와 각도 정보를 수동으로 추가해야 합니다. 그렇지 않으면 프로그램이 틀릴 수 있습니다.
표준 json 데이터:
  • {
  •     "AssetList": [{
  •         "Name": "Chair 1",
  •         "Source": "Prefabs/Chair001.unity3d",
  •         "Position": [2,0,-5],
  •         "Rotation": [0.0,60.0,0.0]
  •     },
  •     {
  •         "Name": "Chair 2",
  •         "Source": "Prefabs/Chair001.unity3d",
  •         "Position": [1,0,-5],
  •         "Rotation": [0.0,0.0,0.0]
  •     },
  •     {
  •         "Name": "Vanity",
  •         "Source": "Prefabs/vanity001.unity3d",
  •         "Position": [0,0,-4],
  •         "Rotation": [0.0,0.0,0.0]
  •     }
  •     }]
  • }

  • Unity3D로 웹 기반의 온라인 게임을 제작할 때 불가피하게 기술인 자원 동적 불러오기를 사용할 수 있다.예를 들어 큰 장면의 자원을 불러오려면 게임의 시작에서 사용자가 모든 자원의 불러오기를 장시간 기다리게 해서는 안 된다.사용자 부근의 장면 자원을 우선적으로 불러와야 한다. 게임 과정에서 조작에 영향을 주지 않는 상황에서 모든 불러오기가 끝날 때까지 백엔드에 남은 자원을 불러와야 한다.코드를 설명하기 전에 먼저 이런 온라인 게임의 개발 과정을 상상해 보세요.먼저 미공은 장면 자원의 3D 모델링을 제작한다. 게임 디자이너는 3D 모델링을 Unity3D로 이끌고 편집 장면을 잡아당겨 완성한 후에 각각의 게임object를 XXX로 내보낸다.unity3d 형식의 자원 파일(BuildPipeline 참조)과 전체 장면의 정보를 설정 파일, xml 또는 Json 형식으로 생성합니다(본문은 Json을 사용합니다).마지막으로 자원 파일과 장면 설정 파일을 서버에 업로드해야 하기 때문에 CMS 관리를 사용하는 것이 가장 좋다.클라이언트가 게임을 실행할 때 먼저 서버의 장면 설정 파일을 읽고 게이머의 위치에 따라 서버에서 해당하는 자원 파일을 다운로드하고 불러온 다음에 게임을 시작한다. 여기는 모든 장면 자원을 다운로드하는 것이 아니라는 것을 주의해야 한다.게임이 진행되는 동안 백엔드에서 모든 리소스가 로드될 때까지 리소스를 계속 로드합니다.json.txt: (주: 생성된 json을 읽을 수 없을 때 인코딩 형식을 바꾸어 ANSI로 바꾸는 것을 잊지 마세요) {"AssetList": [{"Name": "Sphere""Source": "Prefabs/Sphere.unity 3d"}, {"Name": "ANSetetList": ":"[Name":"Sphere. unity 3d"}, {"{"Name": "Name": "Name": ":": ":"ANSeteteteteList":": ":": "AnsetetsetList": ":": ":": "[AnsetsetsetList": ":": ":": ":": 3d"}
    마스터 프로그램:

    using UnityEngine;  using System.Collections;    public class MainMonoBehavior : MonoBehaviour {        public delegate void MainEventHandler(GameObject dispatcher);      public event MainEventHandler StartEvent;      public event MainEventHandler UpdateEvent;      public void Start()      {          ResourceManager.getInstance().LoadSence("Scenes/json.txt");//json          if(StartEvent != null)          {              StartEvent(this.gameObject);          }      }      public void Update()      {          if (UpdateEvent != null)          {              UpdateEvent(this.gameObject);          }      }  }

     
     

        这里面用到了C#的事件机制,大家可以看看我以前翻译过的国外一个牛人的文章。C# 事件和Unity3D在 start方法里调用ResourceManager,先加载配置文件。每一次调用update方法,MainMonoBehavior会把update 事件分发给ResourceManager,因为ResourceManager注册了MainMonoBehavior的update事件。

    ResourceManager.cs  using UnityEngine;  using System.Collections;  using System.Collections.Generic;  using LitJson;  using System.Net;  public class ResourceManager  {    // Use this for initialization          private MainMonoBehavior mainMonoBehavior;          private   string mResourcePath;          private Scene mScene;          private Asset mSceneAsset;          private static ResourceManager resourceManager=new ResourceManager();// new          private Dictionary<string ,WWW > wwwCacheMap=new Dictionary<string,WWW>();//         public static  ResourceManager getInstance( )          {                  return resourceManager;//          }          public  ResourceManager()          {                  mainMonoBehavior = GameObject.Find("Main Camera").GetComponent<MainMonoBehavior>();                  mResourcePath ="file://"+Application.dataPath+"/..";          }                  public void LoadSence(string fileName)          {                  //Debug.Log(fileName);                  mSceneAsset = new Asset();                  mSceneAsset.Type = Asset.TYPE_JSON;//                  mSceneAsset.Source = fileName;                  mainMonoBehavior.UpdateEvent += OnUpdate;//          }                public void OnUpdate(GameObject dispatcher)// , ( MainMonoBehavior start LoadSence )          {                  if (mSceneAsset != null)// new                  {                          LoadAsset(mSceneAsset);// , www new                          if (!mSceneAsset.isLoadFinished)//C# bool false                          {                                 return;                          }                          mScene = null;                          mSceneAsset = null;                  }                  mainMonoBehavior.UpdateEvent -= OnUpdate;// , 。          }          //       private Asset LoadAsset(Asset asset)          {                  string fullFileName =mResourcePath+"/"+ asset.Source;// mResourcePath + "/" + asset.Source;                  Debug.Log("fullFileName=" + fullFileName);                  //if www resource is new, set into www cache                  if (!wwwCacheMap.ContainsKey(fullFileName))                  {//                          if (asset.www == null)                          {// www new                                  asset.www = new WWW(fullFileName);                                  return null;                          }                          if (!asset.www.isDone)                          {                                  return null;                          }                          wwwCacheMap.Add(fullFileName, asset.www); // , Unity3D , , 。                                    if (asset.Type == Asset.TYPE_JSON)                  { //Json txt                          if (mScene == null)                          {                                     string jsonTxt = mSceneAsset.www.text;                              Debug.Log("jsonTxt=" + jsonTxt);                              mScene = JsonMapper.ToObject<Scene>(jsonTxt);//mScene Asset , Json AssetList , , Asset txt                // JsonMapper                           }                          //load scene                          foreach (Asset sceneAsset in mScene.AssetList)                          {                                  if (sceneAsset.isLoadFinished)                                  {                                          continue;                                  }                                  else                                  {                                          LoadAsset(sceneAsset);// Asset.TYPE_GAMEOBJECT ,                                          if (!sceneAsset.isLoadFinished)                                          {                                              return null;                                           }                                   }                          }                  }                  else if (asset.Type == Asset.TYPE_GAMEOBJECT)// , GameObject , ,Asset                  //TYPE_GAMEOBJECT                  { //Gameobject                          if (asset.gameObject == null)// null wwwCacheMap (fullFileName , GameObject ),                          {                                  wwwCacheMap[fullFileName].assetBundle.LoadAll();// new WWW ,                                  GameObject go = (GameObject)GameObject.Instantiate(wwwCacheMap[fullFileName].assetBundle.mainAsset);                                  UpdateGameObject(go, asset);                                  asset.gameObject = go;                          }                          if (asset.AssetList != null)//                          {                                  foreach (Asset assetChild in asset.AssetList)                                  {                                          if (assetChild.isLoadFinished)                                          {                                                  continue;                                          }                                          else                                          {                                                  Asset assetRet = LoadAsset(assetChild);                                                  if (assetRet != null)// if else GameObject , 。                                                  {                                                          assetRet.gameObject.transform.parent = asset.gameObject.transform;                                                  }                                                  else                                                  {                                                          return null;                                                  }                                          }                                  }                          }                  }                  asset.isLoadFinished = true;                  return asset;          }          private void UpdateGameObject(GameObject go, Asset asset)          {                  //name                  go.name = asset.Name;                  //position                  Vector3 vector3 = new Vector3((float)asset.Position[0], (float)asset.Position[1], (float)asset.Position[2]);                  go.transform.position = vector3;                  //rotation                 vector3 = new Vector3((float)asset.Rotation[0], (float)asset.Rotation[1], (float)asset.Rotation[2]);                  go.transform.eulerAngles = vector3;          }  }

    View Code  Asset.cs  using UnityEngine;  using System.Collections.Generic;  public class Asset  {          public const byte TYPE_JSON = 1;          public const byte TYPE_GAMEOBJECT = 2;          public Asset()          {              //default type is gameobject for json load              Type = TYPE_GAMEOBJECT;          }          public byte Type          {              get;              set;          }          public string Name          {              get;              set;          }          public string Source          {              get;              set;          }          public double[] Bounds          {              get;              set;          }                  public double[] Position          {              get;              set;          }          public double[] Rotation          {              get;              set;          }          public List<Asset> AssetList          {              get;              set;          }          public bool isLoadFinished          {              get;              set;          }          public WWW www          {              get;              set;          }          public GameObject gameObject          {              get;              set;          }  }  Scene.cs  using System.Collections.Generic;    public class Scene  {          public List<Asset> AssetList          {              get;              set;          }  }

      .unity3d  :

    View Code  using UnityEngine;  using UnityEditor;  using System.IO;  using System;  using System.Text;  using System.Collections.Generic;  using LitJson;  public class BuildAssetBundlesFromDirectory  {        static List<JsonResource> config=new List<JsonResource>();        static Dictionary<string, List<JsonResource>> assetList=new Dictionary<string, List<JsonResource>>();          [@MenuItem("Asset/Build AssetBundles From Directory of Files")]// "@",          static void ExportAssetBundles ()          {//                     assetList.Clear();                     string path = AssetDatabase.GetAssetPath(Selection.activeObject);//Selection                    Debug.Log("Selected Folder: " + path);                                    if (path.Length != 0)                    {                             path = path.Replace("Assets/", "");// AssetDatabase.GetAssetPath Assets/ , , 。                              Debug.Log("Selected Folder: " + path);                             string [] fileEntries = Directory.GetFiles(Application.dataPath+"/"+path);// Application.dataPath " /Assets"                                                         string[] div_line = new string[] { "Assets/" };                             foreach(string fileName in fileEntries)                             {                                      j++;                                      Debug.Log("fileName="+fileName);                                      string[] sTemp = fileName.Split(div_line, StringSplitOptions.RemoveEmptyEntries);                                      string filePath = sTemp[1];                                       Debug.Log(filePath);                                      filePath = "Assets/" + filePath;                                      Debug.Log(filePath);                                      string localPath = filePath;                                      UnityEngine.Object t = AssetDatabase.LoadMainAssetAtPath(localPath);                                                                           //Debug.Log(t.name);                                      if (t != null)                                      {                                              Debug.Log(t.name);                                              JsonResource jr=new JsonResource();                                              jr.Name=t.name;                                              jr.Source=path+"/"+t.name+".unity3d";                                                Debug.Log( t.name);                                              config.Add(jr);// json                                                string bundlePath = Application.dataPath+"/../"+path;                                                 if(!File.Exists(bundlePath))                                                  {                                                     Directory.CreateDirectory(bundlePath);// Asset                                                  }                                                bundlePath+="/"  + t.name + ".unity3d";                                               Debug.Log("Building bundle at: " + bundlePath);                                               BuildPipeline.BuildAssetBundle(t, null, bundlePath, BuildAssetBundleOptions.CompleteAssets);// .unity3d                                      }                             }                              assetList.Add("AssetList",config);                              for(int i=0;i<config.Count;i++)                              {                                      Debug.Log(config[i].Source);                              }                    }                  string data=JsonMapper.ToJson(assetList);//                  Debug.Log(data);          string jsonInfoFold=Application.dataPath+"/../Scenes";          if(!Directory.Exists(jsonInfoFold))          {              Directory.CreateDirectory(jsonInfoFold);// Scenes          }                  string fileName1=jsonInfoFold+"/json.txt";                  if(File.Exists(fileName1))                  {                      Debug.Log(fileName1 +"already exists");                      return;                  }                  UnicodeEncoding uni=new UnicodeEncoding();                                     using FileStream  fs=File.Create(fileName1))//                  {                          fs.Write(uni.GetBytes(data),0,uni.GetByteCount(data));                          fs.Close();                  }        }  }

    좋은 웹페이지 즐겨찾기