- Home /
How to call Class specific methods from an object stored in a GameObject[]?
Hey all.
I'm brand new to Unity, so I'm just doing a Tic Tac Toe game to learn the basics.
Everything is working up until I try to reference a Square in the array. I'm having trouble finding a way to store object (Square) references in such a way they can be accessed from their container, called Square_Boss, which is just an empty GameObject with an attached script. The Squares are Cubes I have all set up in the editor; a 2D scene.
I plan to use Square_Boss to hold the win condition logic, which is why I need the array in the first place.
public class Square_Boss : MonoBehaviour
{
public GameObject[] squares;
//initialization
void Start ()
{
squares = GameObject.FindGameObjectsWithTag ("SQU");
}
public static void Win ()
{
int[] states = new int[9];
for (int i = 0; i < squares.Length; i++) {
states [i] = squares [i].getClickedBy ();
Debug.Log (states [i]);
}
}
}
The Square class looks like this:
public class Square : MonoBehaviour
{
private bool isClicked = false;
private int clickedBy = 0;
private Color[] theColors = {Color.white, Color.red, Color.blue};
private static int playerNumber = 1;
private static int clicks = 0;
// Use this for initialization
void Start ()
{
renderer.material.color = theColors [0];
}
private void OnMouseDown ()
{
if (clicks < 9) {
if (!isClicked) {
SetState ();
}
}
else SendMessageUpwards("Win");
}
private void SetState ()
{
if (playerNumber == 1) {
renderer.material.color = theColors [1];
} else {
renderer.material.color = theColors [2];
}
isClicked = true;
clickedBy = playerNumber;
ChangePlayer ();
}
private void ChangePlayer ()
{
if (playerNumber == 1) {
playerNumber = 2;
} else {
playerNumber = 1;
}
}
public bool getClicked ()
{
return isClicked;
}
public int getClickedBy ()
{
return clickedBy;
}
}
How do I make it so I can store references to the Squares and call their public methods from the Square_Boss script? When I try to make the array type Square[] it gives me an error about implicit casting or something (can't remember exactly, I tried that a while ago).
This is my first question on here, so I apologize for the noob mistakes. I looked around for answers but none of them made sense to me out of context. Also, sorry if the indents are weird... I made the mistake of telling MonoDevelop to format my code for me. =P
Answer by Graham-Dunnett · Sep 04, 2014 at 09:36 AM
See: http://docs.unity3d.com/Manual/ControllingGameObjectsComponents.html
Basically, classes you write derive from Component
. Think of your script/class as being a component.