G
G
GingerSibe2022-03-22 14:11:10
Unity
GingerSibe, 2022-03-22 14:11:10

How can I implement the best way to check if it is in a trigger?

Hello, 2D game, here I have a player, I need to create a spawner in which a cookie (hilka) will appear,
when the player takes it and moves away from it, a new cookie should appear in a couple of seconds, the question is how to correctly implement the check "Is there already a cookie in the spawner, if not, then spawn" and "if a cookie spawns, then the next object should not be a cookie, but for example a glass", the cookie itself appears as a child object of the spawner, but I can't properly implement the check.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Farawa, 2022-03-22
@GingerSibe

make a common Item class and inherit cookies and glasses from it and destroy it when you use it

public abstract class Item : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.layer == 6)//тут введи номер слоя игрока
        {
            UseItem();
        }
    }

    protected abstract void UseItem();

    private void OnDestroy()
    {
        transform.parent.GetComponent<Spawner>().OnItemUse?.Invoke();
    }
}

public class Spawner : MonoBehaviour
{
    [SerializeField] private float spawnDelay = 2f;
    [SerializeField] private GameObject[] items;
    private float lastSpawn;
    public Action OnItemUse;
    private int lastItemIndex = -1;

    private void Start()
    {
        var index = UnityEngine.Random.Range(0, items.Length);
        SpawnItem(index);
        OnItemUse += delegate { StartCoroutine(SpawnItemCoroutine()); };
    }

    private IEnumerator SpawnItemCoroutine()
    {
        int index = 0;
        while (index != lastItemIndex)
        {
            index = UnityEngine.Random.Range(0, items.Length);
        }
        if (lastSpawn + spawnDelay > Time.time)
        {
            float waitTime = Time.time - lastSpawn + spawnDelay;
            yield return new WaitForSeconds(waitTime);
        }
        SpawnItem(index);
    }
    private void SpawnItem(int index)
    {
        Instantiate(items[index], transform);
        lastSpawn = Time.time;
    }
    private void OnDestroy()
    {
        OnItemUse = null;
    }
}
public class Cookie : Item
{
    protected override void UseItem()
    {
        //твой код
        Destroy(gameObject);
    }
}

didn't test it, but in theory it should work

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question