- Home /
Script filling Scene with empty gameObjects
I'm writing a(n incredibly inefficient, I'm guessing) script for seeing if a King is 'in check' in my chess game. Problem is, everytime I run the script it adds 2 New Game Objects to the Scene. Any help appreciated (including streamlining)!
private bool CheckForCheck()
{
GameObject whiteKing = new GameObject();
GameObject blackKing = new GameObject();
ArrayList whitePieces = new ArrayList ();
ArrayList blackPieces = new ArrayList ();
GameObject[] kings = GameObject.FindGameObjectsWithTag("King");
foreach (var king in kings)
{
if (king.GetComponent<PawnBehaviourScript> ().colour == "White")
whiteKing = king;
else
blackKing = king;
}
kings = null;
PawnBehaviourScript[] p = FindObjectsOfType<PawnBehaviourScript> ();
foreach (PawnBehaviourScript piece in p)
{
if (piece.tag != "King")
{
if (piece.colour == "White")
{
whitePieces.Add (piece);
}
else
{
blackPieces.Add(piece);
}
}
}
p = null;
foreach (PawnBehaviourScript whitePiece in whitePieces)
if (whitePiece.CheckMove (FindContainingZone (blackKing)))
{
whiteKing = null;
blackKing = null;
whitePieces = null;
blackPieces = null;
inCheck.SetActive (true);
return true;
}
foreach (PawnBehaviourScript blackPiece in blackPieces)
if (blackPiece.CheckMove (FindContainingZone (whiteKing)))
{
whiteKing = null;
blackKing = null;
whitePieces = null;
blackPieces = null;
inCheck.SetActive (true);
return true;
}
inCheck.SetActive (false);
return false;
}
Answer by $$anonymous$$ · May 31, 2016 at 06:54 AM
In the first two lines of your code you create two gameobjects. These will be instantiated in the root of your hierarchy each time you run the code. I guess you just want a reference to the gameobject king. Change the first two lines of code into:
GameObject whiteKing;
GameObject blackKing;
You now created just a reference, not a complete new gameobject with a reference.
Thanks for the reply. It creates an error if I remove the "= new GameObject()" part: "Use of unassigned local variable"
Answer by dreinzy · May 31, 2016 at 10:22 AM
Moving
GameObject whiteKing = new GameObject();
GameObject blackKing = new GameObject();
outside of the method seems to have fixed it.
Your answer