[英]Instantiating a list of gameobjects in Unity C#
如何使用c#实例化Unity3D中GameObject的列表? 我在检查器窗口中手动填充了预制件列表。
下面是我在Deck.cs中编写的代码,但是我得到“对象引用未设置为对象的实例”。 如果您有阵列解决方案,也将不胜感激。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
namespace Assets
{
class Deck:MonoBehaviour
{
public List<GameObject> deck;
public void Fill()
{
GameObject c1 = Instantiate(deck[0]);
GameObject c2 = Instantiate(deck[1]);
GameObject c3 = Instantiate(deck[2]);
GameObject c4 = Instantiate(deck[3]);
GameObject c5 = Instantiate(deck[4]);
GameObject c6 = Instantiate(deck[5]);
}
}
}
我也尝试使用数组来做,并且得到“您要实例化的对象为空”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
namespace Assets
{
class Deck:MonoBehaviour
{
public GameObject card1;
public GameObject card2;
public GameObject card3;
public GameObject card4;
public GameObject card5;
public GameObject card6;
public GameObject[] deck;
public void Start ()
{
deck = new GameObject[5];
GameObject c1 = Instantiate(card1) as GameObject;
GameObject c2 = Instantiate(card2) as GameObject;
GameObject c3 = Instantiate(card3) as GameObject;
GameObject c4 = Instantiate(card4) as GameObject;
GameObject c5 = Instantiate(card5) as GameObject;
GameObject c6 = Instantiate(card6) as GameObject;
}
}
}
考虑到您的评论,并且您提供的第一个脚本可以完美运行而没有任何错误(应该这样做:没有理由应该返回错误),我觉得您是Unity的新手。
因此,我建议您先阅读Unity教程(它们做得很好,将帮助您了解引擎的基础知识)。 您可以在此处找到“ 滚球教程” 。
关于您的问题:
1-在第一个脚本中,未在任何地方调用Fill()
方法,您必须执行以下操作:
private void Start()
{
Fill();
}
2-此Start()
方法来自MonoBehaviour
父类(以及每帧都调用一次的Update()
方法),并且在场景开始时调用一次。 查看此图表以了解如何进行统一流动。
3-使用List<GameObject>
或GameObject[]
完全取决于您的情况:如果集合的大小要更改,请获取列表。 否则建议使用数组。
4-考虑到您的脚本,我猜是这样的:
namespace Assets
{
class Deck : MonoBehaviour
{
[SerializeField]
private GameObject[] deck;
private GameObject[] instanciatedObjects;
private void Start()
{
Fill();
}
public void Fill()
{
instanciatedObjects = new GameObject[deck.Length];
for (int i = 0; i < deck.Lenght; i++)
{
instanciatedObjects[i] = Instanciate(deck[i]) as GameObject;
}
}
}
}
当然,您仍然可以根据需要使用列表:)
编辑:
如果要使用列表,则只需要:
private GameObject[] instanciatedObjects;
private List<GameObject> instanciatedObjects;
instanciatedObjects = new GameObject[deck.Length];
通过instanciatedObjects = new List<GameObject>();
instanciatedObjects[i] = Instanciated(deck[i]) as GameObject;
替换instanciatedObjects[i] = Instanciated(deck[i]) as GameObject;
通过instanciateObjects.Add(Instanciated(deck[i]) as GameObject);
希望这可以帮助,
使用foreach遍历您的列表与预制件,像这样:
public List<GameObject> Deck = new List<GameObject>(); // im assuming Deck is your list with prefabs?
public List<GameObject> CreatedCards = new List<GameObject>();
void Start()
{
Fill();
}
public void Fill()
{
foreach(GameObject _go in Deck)
{
GameObject _newCard = (GameObject)Instantiate(_go);
CreatedCards.Add(_newCard);
}
}
用大写字母命名列表也是一个好习惯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.