Hi, I’m currently working on a project with switching between different shapes when certain amount of clicks is reached, but when it’s reached, the new shape is spawned, but the old one remains active as well and the random child variable is still taken into account only the first shape, not the next one.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class ShapeManager : MonoBehaviour
{
// timer
public Text countdown;
public float currentTime = 0f;
public float startTime = 100f;
// random point variables
public GameObject[] child; // array of children gameobjects
public GameObject RandomChild; // random gameobject to be shown
int randInt; // random integer for random element
// shapes
public GameObject[] shapes; // all shapes in one array
public int clickAmount = 0; // how many times has player hit the random point
public int currentShape = 0; // index of current shape to be spawned
public int[] shapeClicks = {4,10,18,28,40,54,70,88,102,142, int.MaxValue}; // amount of clicks
private float[] time = { 1, 0.95f, 0.85f, 0.75f, 0.65f, 0.55f, 0.45f, 0.35f, 0.25f, 0.15f, 0.05f }; // time needed for player to click on each shape
void Start()
{
currentTime = startTime;
Instantiate(shapes[0]);
shapes[0].SetActive(true);
child = GameObject.FindGameObjectsWithTag("Collision_Collider"); // used after spawning new object
GenerateRandomPoint(); // after spawning new object
}
void Update()
{
Click();
Timer();
}
void Timer()
{
currentTime -= 1 * Time.deltaTime;
countdown.text = currentTime.ToString("F2");
if (currentTime <= 0)
{
currentTime = 0;
for (int i = 0; i < child.Length; i++)
{
child[i].SetActive(false);
}
countdown.text = ("Game over"); // game over screen
}
if (currentTime < 0.5)
{
countdown.color = Color.red; // text color
}
}
void Click()
{
if (Input.GetMouseButtonDown(0)) // mouse input
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 mousePos2D = new Vector2(mousePos.x, mousePos.y);
RaycastHit2D hit = Physics2D.Raycast(mousePos2D, Vector2.zero);
if (hit.transform.gameObject == RandomChild)
{
clickAmount++;
Debug.LogWarning("Click # " + clickAmount);
if (currentTime > 0)
{
if (clickAmount < shapeClicks[currentShape]){
RandomChild.SetActive(false);
currentTime = 10f; // reset timer FIX
}
else
{
// destroy current one, spawn new
Destroy(shapes[currentShape]);
currentShape++;
Instantiate(shapes[currentShape]);
child = GameObject.FindGameObjectsWithTag("Collision_Collider"); // used after spawning new object
}
GenerateRandomPoint();
}
}
}
}
void GenerateRandomPoint()
{
for (int i = 0; i < child.Length; i++)
{
child[i].SetActive(true); ;
}
randInt = Random.Range(0, child.Length);
RandomChild = child[randInt];
for (int i = 0; i < child.Length; i++)
{
if (child[i] == RandomChild)
{
child[i].SetActive(true); ;
}
else
{
child[i].SetActive(false); ;
}
Debug.Log("Child is " + child[i].name);
}
Debug.Log("Random child is " + RandomChild.name);
}
}