如何将资产目录中的所有预制件列为预制件而不是字符串?

时间:2017-05-10 16:31:10

标签: c# unity3d unity5

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class Prefabs : MonoBehaviour
{

    List<GameObject> prefabs = new List<GameObject>();

    // Use this for initialization
    void Start ()
    {
        var resourcesPath = Application.dataPath;
        var absolutePaths = System.IO.Directory.GetFiles(resourcesPath, "*.prefab", System.IO.SearchOption.AllDirectories);
        foreach (var absolutePath in absolutePaths)
        {
            var prefab = Path.GetFileName(absolutePath);
            prefabs.Add(prefab);
        }
    }

    // Update is called once per frame
    void Update () {

    }
}

问题是变量预制是一个字符串,列表是GameObject类型。我希望所有的预制件不是作为琴弦而是作为预制件。

更新

我将所有预制件移动到路径Asstes / Resources 但是我得到了0个预制件。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class Prefabs : MonoBehaviour
{
    // Use this for initialization
    void Start ()
    {
        var pres = Resources.LoadAll<GameObject>("Assets/Resources/");
    }
}

变量pres为空。 我想在资源文件夹资源和子目录中获取所有预制件。

2 个答案:

答案 0 :(得分:0)

您可以创建一个派生自GameObject类的新类。在新课程中,您可以添加字符串属性。

例如:

public class MyGameObject : GameObject{

   public MyGameObject() : base(){

       Console.WriteLine("Calls constructor from base class and this!");
   }

   public string MyPath {get; set;}
}

然后你可以使用你的课程,如下:

List<MyGameObject> prefabs = new List<MyGameObject>();
foreach (var absolutePath in absolutePaths)
{
    var prefab = Path.GetFileName(absolutePath);
    prefabs.Add(new MyGameObject(){MyPath = prefab);
}

如果你想玩这个星座,请看这里:https://dotnetfiddle.net/Y1KPpU

答案 1 :(得分:0)

假设您使用的是Unity5,请查看AssetDatabase.LoadAssetAtPath。 https://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAssetAtPath.html

...来自链接页面:

static void ImportExample()
    {
        Texture2D t = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/Textures/texture.jpg", typeof(Texture2D));
    }

关于如何使用的页面有一个非常好的解释。注意注意事项,因为“只使用正斜杠”这样的事情非常重要! 另请注意,这是在UnityEditor命名空间中(通常不包含在构建中),因此您可能需要围绕它#if

#if (UNITY_EDITOR) 
... your class/code ...
#endif
相关问题