如何获得GameObject的变量名

时间:2019-05-26 00:07:39

标签: c# unity3d game-development

我有一个GameObject列表。我正在做的是每当实例化存储在GameObject变量中的预制件,然后在以后销毁它。

List<GameObject> listofGameObject;
blueLine = Instantiate(monitorShapes, transform.position, transform.rotation);

然后,稍后我将使用listofGameObject [2]访问该GameObject。我想要实现的是获取存储在listofGameObject的索引2中的GameObject的变量名称,即blueLine。我尝试使用listofGameObject [2] .name,但它返回资产中的预制名称。

3 个答案:

答案 0 :(得分:0)

会生成带有预制资产名称的预制件。

是否有任何包含变量名称blueLine的脚本?如果是,那么您可能需要在引用变量名称之前获取该组件。

示例。

List<GameObject> listofGameObject;
blueLine = Instantiate(monitorShapes, transform.position, transform.rotation);

-- listofGameObject[2].GetComponent<[ScriptName]>().variableName;

让我知道是否有帮助

答案 1 :(得分:0)

为什么您确切需要获取变量名?您可以从列表中删除游戏对象,将其存储在游戏对象中,然后销毁该游戏对象。

所以代码看起来像这样:

//Creates the list
List<GameObject> listOfGameObjects = new List<GameObject>();
//Creates the blueLine GameObject
blueLine = Instantiate(monitorShapes, transform.position, transform.rotation);
//Adds the blueLine object to the list
listOfGameObjects.Add(blueLine);

然后,当您要从列表中删除对象时,请执行以下操作:

//Removes the blueLine object from the list
listOfGameObjects.Remove(blueLine);
//Destroys the blueLine Object from the scene
Destroy(blueLine);

我希望这是您正在寻找的解决方案

答案 2 :(得分:0)

实例化后,将GameObject的名称设置为变量名称

blueLine = Instantiate(monitorShapes, transform.position, transform.rotation);
blueLine.name = nameof(blueLine);