Reputation: 33
First time question here.
I'm trying to build a game board like one you would see playing chess. I've made two scripts, one that spawns the board and stores each instantiated tile in a 2d array. And another script that sets the row and column location and onMouseOver
prints that location to the console. However this is always print Row = 0
and Col = 0
.
I've come to the conclusion that the 2d array is just setting a clone in memory and therefor the stored values I set via calling the function setRC();
are not being being found as the instantiated objects the the Unity scene don't share the memory location.
Anyone have an idea as to how I can fix this?
public class Map : MonoBehaviour {
public static int Row = 7;
public static int Col = 7;
private GameObject[,]boardPiece = new GameObject[Row,Col];
public GameObject prefab;
public GameObject prefab2;
void Start () {
for (int i = 0; i < Row; i++) {
for (int j = 0; j < Col; j++)
{
if(i%2 ==1 && j%2 ==1 || i%2 ==0 && j%2 ==0)
{
boardPiece[i,j] = (GameObject)Instantiate(prefab, new Vector3(i*4.0f,0,j*4.0f),Quaternion.identity);
}else{
boardPiece[i,j] = (GameObject)Instantiate(prefab2, new Vector3(i*4.0f,0,j*4.0f),Quaternion.identity);
}
boardPiece[i,j].GetComponent<BoardPiece>().setRC(i,j);
}
}
}
}
public class BoardPiece : MonoBehaviour {
private int rowPlace;
private int colPlace;
// Use this for initialization
void Start () {
rowPlace = 0;
colPlace = 0;
}
// Update is called once per frame
void Update () {
}
void OnMouseOver(){
string message = "Row: " + rowPlace + " Col: " + colPlace;
print (message);
}
public void setRC(int R, int C)
{
rowPlace = R;
colPlace = C;
print ("set " + rowPlace + "," + colPlace);
}
}
Upvotes: 3
Views: 830
Reputation: 70671
Without a complete code example (difficult or even impractical to provide for Unity3d projects I know, but still...) it is difficult to know for sure what the problem is. However…
While the Start()
method is often used in a fashion similar to a constructor, it's important to understand that it's not in fact one. I don't think it's called yet by the time your code is calling the setRC()
method on your new object.
This means that the flow of execution is that you first set the row and column values as desired, and then later the BoardPiece.Start()
method is called by the Unity3d framework, setting the row and column values back to 0
.
Since the rowPlace
and colPlace
fields are already set to 0
by default when the object is created, I think the best fix is to just remove those two lines from the Start()
method altogether. They aren't needed, and I believe they are responsible for the problem you are having.
Upvotes: 2