- Home /
IndexOf returning -1 c#
So I have an array of towns set by tags. I am trying to get a return of each specific gameobject in the array, so that I can access that specific gameobject and edit its variable. But when I try to call the return function it doesn't find the array and returns -1. I have a feeling there is a better way to do this, but I'm not good with syntax yet, so I just create what logic I can. here is my indexof return function
public int GetTownArray()
{
town1Index = System.Array.IndexOf (town1Array, this.gameObject);
return town1Index;
}
Here is how I create my array
GameObject[] town = GameObject.FindGameObjectsWithTag("Player 1 Town");
town1Array = new TownScript[town.Length];
for (int i = 0; i < town.Length; i++)
{
town1Array [i] = town [i].GetComponent<TownScript> ();
}
Thanks in advance for any help
Answer by Bunny83 · Jul 12, 2016 at 09:24 PM
Uhm, your "town1Array" is an array of type "TownScript" and you try to find the index of a GameObject reference which doesn't make any sense since a gameobject and a Component are two completely different types.
If there is a "TownScript" on the gameobject you want to find you can do this:
town1Index = System.Array.IndexOf (town1Array, gameObject.GetComponent<TownScript>());
However if your "GetTownArray" method is actually a method inside the TownScript, you can simply do
town1Index = System.Array.IndexOf (town1Array, this);
Answer by Danisuper · Jul 12, 2016 at 09:39 PM
I think you should try with lists
List<GameObject> town=new List<GameObject>();
//assign the list and convert it to list because GameObject.FindGameObjectsWitag returns an array
town=GameObject.FindGameObjectsWitag("Player 1 Town").ToList();
//you'd better call it Town1List instead of Town1Array now lol
List<TownScript> Town1List=new List<TownScript>();
for(int i=0;i<town.Count;i++)
{
GameObject actual_town=town[i];
Town1List.Add(actual_town.GetComponent<TownScript>());
}
//to acces the index
public int GetTownArray(GameObject Town,list MyTownList)
{
int town1Index=MyTownList.IndexOf(Town);
return town1Index;
}
}
IndexOf isn't used to get a specific gameobject. MyList.IndexOf(x) or System.Array.IndexOF(y,x) like you done, will return the index of x, the int. Instead to acces a gameobject in a list you can just do list[index]. And if you make them public you'll be able to see them in the inspector like arrays. Hope it helped :)
Thank you for the idea! If I didn't have to go back and rework a lot of stuff I would, but thus far I've been able to get everything working now. I'll keep it in $$anonymous$$d for the future though! Not the best with syntax but I can understand the logic haha
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Making a bubble level (not a game but work tool) 1 Answer
Random array spawn C# 1 Answer
Array Index Out of Range - Maze Generation Algorithm 1 Answer