hi,
am doing a tic tac toe game, i need help on how to identify the index of a gameobject in an array when the object is clicked. am trying to figure it out but i couldn’t.
also if you could please explain me how it works.
Hi there!
Sorry to hear you’re having trouble. There are quite a few different ways to handle this, but I’ll try to give you the easiest.
Lets create an X and O Manager that holds the array. To do this, follow these steps:
-
Create a new gameObject and name it “Manager”
-
Create a new script called “TicTacToe_Manager” and attach it to the gameObject.
-
Create a tag called “XO”
-
Click each of your X or O gameObjects (or their prefabs) and tag them with “XO” tag.
-
Double click the script and put something like this in it.
//This is the top of the script underneath the class name public GameObject[] myArray; //We make the array public so that we can reference it from other scripts. void Start(){ myArray = GameObject.FindGameObjectsWithTag("XO"); //For each of the gameObjects with the tag "XO" in the scene, add it to the array. }
Next,
-
Create a script called “TicTacToe_Object”
-
Attach it to each of your X or O objects (or the object prefab).
-
Double click the script and type in
the script below://Top of script underneath class name: TicTacToe_Manager XO_Manager; void Start(){ XO_Manager = GameObject.Find("Manager").GetComponent<TicTacToe_Manager>(); } void OnMouseDown(){ //if this object is clicked by the mouse... for(int i = 0;i<XO_Manager.myArray.Length;i++){ //for each object in the array.. if(XO_Manager.myArray_.transform == transform)[ //if that array object's transform is also *this* transform..._
Debug.Log("You just clicked the object with the Index of " + i.ToString(); //Send a message to the console with the ID we just clicked.
}
}
}
Good luck! And let me know if you have any questions.