- Home /
How to obtain a gameObject from an List with the name?
Hey Guys! I'm a bit stuck here. I've a List through which I'm looping and checking to see whether the object I've send through the argument is active or not. If not I'm activating it.
But what I want is to check whether the gameObject with the same name as I'm sending to it is active or not. Is there a way I can do this or not.
Here is my code: public GameObject activateObstacle(int id, string name){
for (int i = 0; i < obstaclePool[id].Count; i++)
{
if(!obstaclePool[id][i].activeInHierarchy)
{
obstaclePool[id][i].SetActive(true);
string spawnedObstacleName = obstaclePool[id][i].gameObject.name;
Debug.Log("spawned obstacle name is " + spawnedObstacleName);
return obstaclePool[id][i];
}
}
}
I want to check whether spawnedObstacleName is similar to the name parameter that I'm sending. And If it is same then do all the stuff like checking whether it is active or not and then activating it.
Please Help. Thank you.
Answer by Loius · Jul 18, 2014 at 04:18 PM
if ( name == spawnedObstacleName ) {
// stuff
}
That said, don't use object names. It's extremely unreliable because someone will make a typo at some point and it will be extremely hard to track down why that's causing an error.
Use custom components with an identifier (like index) if you have to, but names are a last resort.
In your case you want to store the obstacles in a list so you can just send the index and simply not care what the name is.
@Lolus I've tried that inside the forloop earlier. But it didn't work. not going inside the that if statement.
use debug.log to print out the names of the objects. if you think there should be a match and there isn't then you should make sure that you're passing in the right name and all.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Problem to rename gameobject when loading from file. 0 Answers
Find Many GameObjects by name 2 Answers
GameObject.find("name") doesn't work if executed in the same loop of... 1 Answer
Looping through multiple lists 0 Answers