Finding the index of a gameobject by name
Hi, Excuse my foolishness. I'm trying to make it so that the player enters a string and if a gameobject by that name exists, we'll instantiate it. I did the following but of course it doesn't work. I wasn't able to find anything related to this (could be my fault) and I'd like to ask you guys for help.
public string name;
public GameObject inputField;
public List<GameObject> objects;
int object_index;
public Transform player;
public void Creator_Input()
{
name = inputField.GetComponent<Text>().text;
Debug.Log(name);
int indexofcreation = objects.IndexOf(name);
Instantiate(objects[0], new Vector3(player.position.x, player.position.y, player.position.z - 2), Quaternion.identity);
}
Answer by Hellium · Jun 12, 2020 at 09:25 PM
public Text inputField; // Drag & drop the gameObject with the Text component in the inspector
public List<GameObject> objects;
public Transform player;
public void Creator_Input()
{
int objectIndex = objects.FindIndex(gameObject => string.Equals(inputField.text, gameObject.name));
if(objectIndex >= 0)
Instantiate(objects[objectIndex], new Vector3(player.position.x, player.position.y, player.position.z - 2), Quaternion.identity);
}
It underlines the "FindIndex" and says " The type arguments for method "Array.FindIndex(T[], Predicate )" cannot be inferred from the usage. Try specifying the type of arguments explicitly.
$$anonymous$$y bad, I don't know why I used this method since objects
is a List
.... Code fixed
Well that fixed the error in the code but now when I try and execute the function. It says " Object reference not set to an instance of an object". I know that I keep bugging you but I really need help :p
Your answer
![](https://koobas.hobune.stream/wayback/20220613000803im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How can i change my unity ID acc nickname or delete it? PLS HALP 0 Answers
I need help finding the index of an object in a list. 1 Answer
Finding specific index of an array 1 Answer
How do I fix CallNative assembly already imported when building AssetBundles? 1 Answer
C# Array Of Class Read Variables 2 Answers