2D Object Spawn Lag
Hello. I'm extremely new to coding, and I'm having issues with a very simple minigame that I've created. The game, basically, is that you need to tap or click to spawn objects. Thats pretty much it. Once the player clicks or taps quickly, the game starts lagging. I thought that putting a time limit on the objects (so that they disappear after 2 seconds) would fix this--but it doesn't. I've attached the code below. Thanks.
using System.Collections; using System.Collections.Generic; using UnityEngine; // © 2017 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class SpawnOnClick : MonoBehaviour { public GameObject objectToSpawn; // Use this for initialization void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
Vector3 spawnPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
spawnPosition.z = 0.0f;
GameObject objectInstance = Instantiate(objectToSpawn, spawnPosition, Quaternion.Euler(new Vector3(0, 0, 0)));
}
}
}
using UnityEngine; using System.Collections;
public class DestroyByTime : MonoBehaviour { public float lifetime;
void Start ()
{
Destroy (gameObject, lifetime);
}
}
Answer by Guy_Yome · Jul 08, 2018 at 10:38 PM
One quick thing you could do is to Instantiate all the needed objects right at the begining and store their reference into a list or an array, then when needed you just enable them and change their positions, without having to create a new object from scratch everytime.
Okay-- how would I go about doing that? Sorry, I'm extremely new to this.