Spawning object when tag is sliced Unity C#

51 views Asked by At
private IEnumerator Spawn()
{
    yield return new WaitForSeconds(2f);

    while (fruitsSpawned != numberOfFruits)
    {
        GameObject prefab = fruitPrefabs[Random.Range(0, fruitPrefabs.Length)];

        Vector3 position = new Vector3();
        position.x = Random.Range(spawnArea.bounds.min.x, spawnArea.bounds.max.x);
        position.y = Random.Range(spawnArea.bounds.min.y, spawnArea.bounds.max.y);
        position.z = Random.Range(spawnArea.bounds.min.z, spawnArea.bounds.max.z);


        //Diagnoal spawning
        Quaternion rotation = Quaternion.Euler(0f, 0f, Random.Range(minAngle, maxAngle));
        

        GameObject fruit = Instantiate(prefab, position, rotation);
        
        float force = Random.Range(minForce, maxForce);
        fruit.GetComponent<Rigidbody>().AddForce(fruit.transform.up * force, ForceMode.Impulse);

        //Stop objects that have been cut
        if (fruit.tag == "Sliced")
        {   
            Destroy(fruit, maxLifetime);
        }
        fruitsSpawned++;
        yield return new WaitForSeconds(Random.Range(minSpawnDelay, maxSpawnDelay));

    }
}

So I've been working on my project for a while and I feel like my mind has locked, so some help would be really nice.

This is a spawner that spawns fruits and when I slice the fruit (click on it) the tag becomes "Sliced".

My question is how could I spawn fruits only when the tag has been changed.

1

There are 1 answers

0
baguette On

First of, you should not write code that concern destroying fruits in code that spawn fruits, that's a direct violation of SOLID

-> Move that snipped of code out to a GameManager class

Secondly, about your question, I think your intention is spawn new fruits only when the player has scliced at least one fruit right?

-> If Im right, then add a watcher variable to the above GameManager class, that:

  • switch to true everytime a fruit is scliced
  • switch to false with the new fruits spawn