【问题标题】:Instantiate object from list c#从列表 c# 实例化对象
【发布时间】:2016-03-08 23:15:10
【问题描述】:

我是 C# 编程的初学者,我正在尝试 Unity。

当我尝试从数组列表(列表)中实例化 gameObject 随机数时,但出现错误(磁带对象不能用作 top parapete T.)并且我没有找到解决方案。

我有 6 个游戏对象:

public gameobject Red;
public gameobject yellow;
etc... 

到 6。

y cont 有一个用于添加或远程对象的动态数组列表。像这样:

public ArrayList list = new ArrayList();

然后,我添加游戏对象:

list.Add (Red);
list.Add(Yellow);

最后,我从 arraylist 中实例化随机对象(有时对象数量不同)

color = Instantiate(list[random.range(0, list.Length)]);

但是没有找到,并且出现这个错误:

磁带对象不能用作tope parapete T。

【问题讨论】:

  • 首先,我认为不使用ArrayList 而是使用List<gameobject> 可能会有所帮助。这意味着您使用的是强类型列表,这至少可以为您解决一些问题。
  • 您还应该向我们展示Instantiate 方法的代码。

标签: c# list arraylist random


【解决方案1】:

这是一个关于从列表中选择随机项目的问题。让我建议使用List<T> 而不是ArrayList。举个例子:

static void Main()
{
    var Red = new GameObject();
    var Yellow = new GameObject();

    List<GameObject> gameObjects = new List<GameObject>() { Red, Yellow };
    var randomGameObject = gameObjects[(new Random()).Next(gameObjects.Count)];

    // color = Instantiate(randomGameObject)

    //Console.WriteLine(randomGameObject);
    Console.ReadLine();
}

【讨论】:

    【解决方案2】:

    Instantiate 方法可能是这样声明的:

    Color Instantiate(GameObject gameObject)
    {
        // ...
    }
    

    但是ArrayList 不是强类型的,即它返回object 类型的项目。因此,您必须将项目转换为GameObject

    color = Instantiate((GameObject)list[random.range(0, list.Length)]);
    

    但更好的解决方案是使用强类型泛型列表List&lt;GameObject&gt;。它的工作方式很像 ArrayList,但返回类型为 GameObject 的项目。

    public List<GameObject> list = new List<GameObject>();
    list.Add(Red);
    list.Add(Yellow);
    
    color = Instantiate(list[random.range(0, list.Count)]);
    

    【讨论】:

    • 解释得更好,但我发现你对 ArrayList 的使用是宽容的,在你的地方我不建议使用 ArrayList 的解决方案
    • 我不建议使用ArrayList 的解决方案。我展示了如何修复使用ArrayList 的现有解决方案,并建议使用List&lt;GameObject&gt; 作为更好的解决方案。
    猜你喜欢
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 2012-01-31
    • 2011-01-03
    • 1970-01-01
    相关资源
    最近更新 更多