简体   繁体   中英

How to get the variable name of GameObject

I have a list of GameObject. What I'm doing is Whenever I instantiate a prefab I stored in GameObject variable then destroy it later on.

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

Then Later on I'll access that GameObject using listofGameObject[2]. What I'm trying to achieve is get the variable name of the GameObject stored in index 2 of listofGameObject which is blueLine. I tried using listofGameObject[2].name but it returns the name of prefab in asset.

After instantiate, set the name of the GameObject to the variable name

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? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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