- Home /
Instantiating Too Many Objects
I have a turn based strategy game, and it's based on tile movement. I want to put a marker over the tiles the player can move to. I have an array of all the tiles in the map, and then I have a list of the tiles within the move radius. I have a working method for telling and listing which tiles are within the radius, but when I instantiate the markers, it instantiates way too many. Also, I need to do the foreach loop so that the tiles will be placed above each individual one. Any help will be appreciated. Code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MovementController : MonoBehaviour
{
public int moveRadius;
public GameObject[] tilesInGame;
public List<GameObject> tilesToMove = new List<GameObject> ();
public GameObject moveTarget;
void Start()
{
tilesInGame = GameObject.FindGameObjectsWithTag ("Node");
AssignTilesWithinMove ();
}
void Update()
{
}
void AssignTilesWithinMove()
{
foreach (GameObject tile in tilesInGame) {
if (Vector3.Distance (transform.position, tile.transform.position) < moveRadius) {
tilesToMove.Add (tile);
ShowTarget ();
}
}
}
public void Move()
{
}
void ShowTarget()
{
Vector3 offset = new Vector3 (0, 1, 0);
foreach (GameObject tile in tilesToMove) {
GameObject targetMarker = (GameObject)Instantiate (moveTarget, tile.transform.position + offset, Quaternion.Euler(90, 0, 0));
}
}
}
Answer by Lairinus · Oct 08, 2017 at 05:14 AM
You are using a foreach() (ShowTarget) inside of a foreach() (AssignTilesWithinMove). If you have 10 tiles, you are creating 100 markers. If you have 100 tiles, you are creating 10,000.
The bigger problem here is that you are using Instantiate() instead of SetActive(). I would create all of the tiles beforehand, set them as a reference in a script, and then call SetActive() when you need to show them. This is much faster than creating a brand new marker each time.
Your answer
Follow this Question
Related Questions
Translate a 2D position to a 3D space 1 Answer
Instantiate for loop skips some objects 1 Answer
How to Instantiate Objects based on a list of integers 0 Answers
Multiple Fire Points 2 Answers