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);
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 _= town *.GetComponent<TownScript> ();*_
Thanks in advance for any help
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);
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>();
//to acces the index
public int GetTownArray(GameObject Town,list MyTownList)
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