如何将gameObject附加到在具有类定义的脚本中创建的对象



我对如何将gameObject链接到在其附加脚本中创建的对象感到困惑。我已经创建了两个gameObject表。我的目标是将这些表放在列表或数组中,在数组中循环查看它们是否与客户的gameObject冲突,如果是,则将它们从客户可以移动到的表列表中删除。

为了做到这一点,在脚本中,我希望表具有布尔字段";"被占用";,所以我用这个字段创建了一个Table类,并在Start((方法中创建了Table对象。以前,我使用gameObject.FindGameObjectsWithTag("Table")方法将gameObject表添加到数组中,但现在我对如何将表与对象创建联系起来感到困惑,我很确定我从根本上误解了一些东西。

本质上,我想知道:

  1. 如果这些gameObject已经存在于Unity中,我需要在脚本中创建对象吗
  2. 在这种情况下是否没有必要创建类/是否有更合适的方法来定义字段&gameObjects的行为

如有任何建议或解释,我们将不胜感激。

这是代码:

public class TableBehavior : MonoBehaviour
{
[SerializeField] public List<Table> tableList = new List<Table>();
public bool isOccupied;
public int tableNumber;
//Start is called before the first frame update
void Start()
{
//exampleList = gameObject.FindGameObjectsWithTag("Table");

//initializing 3 tables with table numbers (unused), and isOccupied field set to false
Table t1 = new Table(0, false);
Table t2 = new Table(1, false);
Table t3 = new Table(2, false);
tableList.Insert(0, t1);
tableList.Insert(1, t2);
tableList.Insert(2, t3);
}
// Update is called once per frame
void Update()
{
isTableOccupied();
}

// if table is occupied, remove it from list of options customer can move to
public void isTableOccupied()
{
foreach(Table t in tableList)
{
if (t.isOccupied == true)
{ 
tableList.Remove(t);
}         
} 
}
// i want this method to iterate through tableList, and if a collision is detected in game with customer, set isOccupied field to true
void OnCollisionEnter2D(Collision2D collision)
{   
foreach(Table t in tableList)
{
if(collision.gameObject.tag == "customer")
{
Debug.Log("collision detected!");
t.isOccupied = true;

}

}
}
}

你认为你可能误解了什么是对的。但公平地说,Unity中的类(或者更确切地说是MonoBehavior类(在Unity中与在";纯";C#环境。

第一件奇怪的事情是从不使用MonoBehvaiour驱动类的构造函数。创建对象的主要方法是:

  • 实例化
  • GameObject构造函数
  • AddComponent(也可以在编辑器中完成,请参见此处(

对于您的特定情况,我不会使用单独的Table类,而是将所有内容都放在TableBehaviour中。然后有另一个MonoBehavior类,如TableManager,它实例化来自Premab的表。您可以在这个TableManager类中有协调代码,但在TableBehvaiour类中有类似Rest的冲突。

为了学习Unity的一般概念,我可以推荐这个简短的系列教程。

最新更新