Hi! I am still quite a noob when it comes to coding with C#.
I was designing this game, where the player basically cuts grass.
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class tool : MonoBehaviour
{
private SpriteRenderer sprite;
private BoxCollider2D bcollider;
public float timer = 0f;
public float GrowTime = 20.0f;
public float maxSize = 1f;
public float score;
public Text scoretext;
private GameObject grass;
public bool isMaxSize = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void FixedUpdate()
{
UpdateScore();
}
private IEnumerator Grow()
{
Vector2 startScale = grass.transform.localScale;
Vector2 maxScale = new Vector2(maxSize, maxSize);
do
{
grass.transform.localScale = Vector3.Lerp(startScale, maxScale, timer / GrowTime);
timer += Time.deltaTime;
yield return null;
}
while (timer < GrowTime);
isMaxSize = true;
}
public void cooldown()
{
grass.GetComponent<BoxCollider2D>().enabled = true;
}
public void AddScore(int newScore)
{
score += newScore - 1;
}
public void UpdateScore()
{
scoretext.text = "" + score;
}
public void grassrepsawn()
{
grass.GetComponent<SpriteRenderer>().enabled = true;
timer = 0f;
StartCoroutine(Grow());
Invoke(nameof(cooldown), 20f);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "grass")
{
score = score + 1;
print("grasscutted");
grass = collision.gameObject;
collision.gameObject.GetComponent<BoxCollider2D>().enabled = false;
collision.gameObject.GetComponent<SpriteRenderer>().enabled = false;
collision.gameObject.transform.localScale = new Vector3(0.001f, 0.001f, 0.001f);
isMaxSize = false;
Invoke(nameof(grassrepsawn), 2.0f);
}
}
}
This script is inside the hitbox of the tool that the player is holding.
My problem is that when I cut a piece of grass, the code works like normal, but when i try to cut another piece of grass while the first one is still not done growing back, everything breaks.
Does anyone here have suggestions on how to make the script complete fully for each grass block, and not break when another one is cut?
I know the script is messy, sorry about that.
Thank you!