简体   繁体   English

如何获得GameObject的变量名

[英]How to get the variable name of GameObject

I have a list of GameObject. 我有一个GameObject列表。 What I'm doing is Whenever I instantiate a prefab I stored in GameObject variable then destroy it later on. 我正在做的是每当实例化存储在GameObject变量中的预制件,然后在以后销毁它。

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

Then Later on I'll access that GameObject using listofGameObject[2]. 然后,稍后我将使用listofGameObject [2]访问该GameObject。 What I'm trying to achieve is get the variable name of the GameObject stored in index 2 of listofGameObject which is blueLine. 我想要实现的是获取存储在listofGameObject的索引2中的GameObject的变量名称,即blueLine。 I tried using listofGameObject[2].name but it returns the name of prefab in asset. 我尝试使用listofGameObject [2] .name,但它返回资产中的预制名称。

After instantiate, set the name of the GameObject to the variable name 实例化后,将GameObject的名称设置为变量名称

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

The prefabs are spawned with the name of prefab asset. 会生成带有预制资产名称的预制件。

Is there any script that contains the variable name blueLine? 是否有任何包含变量名称blueLine的脚本? If yes, then you may want to get that component before referencing the variable name. 如果是,那么您可能需要在引用变量名称之前获取该组件。

Example. 例。

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

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

Let me know if it helps 让我知道是否有帮助

Why exactly do you need to get the variable name? 为什么确切地需要获取变量名? You can remove the gameobject from the list, store it in a gameobject and then Destroy the gameobject. 您可以从列表中删除游戏对象,将其存储在游戏对象中,然后销毁该游戏对象。

So the code would look something like this: 因此代码看起来像这样:

//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);

Then when you want to delete the object from the list you do the following: 然后,当您要从列表中删除对象时,请执行以下操作:

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

I hope this is the solution you were looking for 我希望这是您正在寻找的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM