如何向一个GameObject添加变量? GameObjects有一系列的变量(名称,转换等),可以从任何脚本中访问和修改。我该如何添加一个变量,例如“颜色”或“类型”,以便在其他脚本中可以访问或修改。 谢谢。
如何向一个GameObject添加变量? GameObjects有一系列的变量(名称,转换等),可以从任何脚本中访问和修改。我该如何添加一个变量,例如“颜色”或“类型”,以便在其他脚本中可以访问或修改。 谢谢。
GameObject
不是一个密封类,那么继承可能是解决问题的方法。在这种理想情况下,您可以尝试以下操作。public class ExtraGameObject : GameObject
{
// Logically you could make use of an enum for the
// color but I picked the string to write this example faster.
public string Color { get; set; }
}
public class ExtraGameObject
{
public string Color { get; set; }
public GameObject GameObject { get; set; }
}
我知道这不完全是您想要的,但我认为由于GameObject
的封闭性质,无法实现您的想法。
ExtraGameObject':无法从密封类型
UnityEngine.GameObject'派生”。我猜像Seth说的那样,变量不能添加到GameObject中。 - cubecubeChristos的回答是正确的。你不能向GameObject数据类型添加变量,因为它作为基础内置到语言中。要向预制数据类型添加变量,请从它们扩展。有关继承的更多信息,请参见
您可以使用Instantiate方法将脚本添加到预制体中,从而创建对象。在此脚本中,您声明公共变量。 然后,您可以使用GetComponent方法更改和获取此变量的值。
将以下代码添加到预制体(预制体名称为thatPrefab
,脚本文件名为IdDeclarer
)中作为组件:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IdDeclarer : MonoBehaviour
{
public int id;
}
声明对象的特征(例如ID):
GameObject newObject = Instantiate(thatPrefab, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
newObject.GetComponent<IdDeclarer>().id = 99;
Debug.Log(newObject.GetComponent<IdDeclarer>().id);
输出:99
希望对你有所帮助