Strange results with FindGameObjectsWithTag()
Hello,
I have a strange problem with FindGameObjectsWithTag(), maybe someone can help.
I'm building a 2D game where the player can right click on the screen to open a context menu. This context menu has different buttons and when the user clicks a button, a GameObject is added to the level. When the player presses the space bar, the ball starts to move. When the space bar is pressed again, the added GameObjects should be saved and the level has to restart.
When I count the added GameObjects inside of the Update() method I get the correct result, but when I count them inside my SavePlacedObjects() method the number is always 2 too high and I have no idea why. (so when I added 1 object it's 3, when I added 2 objects it's 4 and so on)
EDIT: What's even more strange is the following behaviour:
When I place one object to the level and restart the scene I get "saving 3 objects".
But when I place one object to the level, pause the game, click on the placed object in my GameObject list and then restart the scene I get the correct value of "saving 1 objects".
I'm confused...
void Update ()
{
// gives the correct value
GameObject[] placedObjects = GameObject.FindGameObjectsWithTag ("Obstacle");
print (placedObjects.Length + " placed");
// open context menu
if (Input.GetMouseButtonDown(1)) {
OpenContextMenu ();
}
// close context menu
if (Input.GetMouseButtonDown(0)) {
if (EventSystem.current.IsPointerOverGameObject () == false) {
CloseContextMenu ();
}
}
// start the ball
if (Input.GetKeyDown (KeyCode.Space)) {
// restart the level when the ball rolls and space is pressed
if (ballRigidbody.gravityScale > 0) {
SavePlacedObjects ();
SceneManager.LoadScene (SceneManager.GetActiveScene ().name);
}
else {
ballRigidbody.gravityScale = ballGravity;
}
}
}
And here the SavePlacedObjects() method:
private void SavePlacedObjects ()
{
globalObject.placedObjects.Clear ();
// result is always too high by 2
GameObject[] placedObjects = GameObject.FindGameObjectsWithTag ("Obstacle");
print ("saving " + placedObjects.Length + " objects");
foreach (GameObject go in placedObjects) {
globalObject.placedObjects.Add (go);
}
}
Your answer