using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RandomDuple : MonoBehaviour {

    public string duplename;
    public int max;
    public float dist;
    public bool already;

    public void Update()
    {
        if (already) return;
        GameObject plauer = GameObject.Find("player");
        if (plauer == null) return;

        if (Vector3.Distance(plauer.transform.position, transform.position) < dist &&
            Random.Range(0,15) == 0)
        {
            RaycastHit2D rh2d = Physics2D.Raycast(transform.position, (plauer.transform.position - transform.position).normalized, dist, ~(LayerMask.GetMask("enemy") | (2<<Physics.IgnoreRaycastLayer)));
            if (rh2d.rigidbody != plauer.GetComponent<Rigidbody2D>()) return;
            RandomDuple[] alls = GameObject.FindObjectsOfType<RandomDuple>();
            int count = 0;
            for (int i = 0; i < alls.Length; i++)
            {
                if (alls[i].duplename == duplename) count++;
            }
            if (count < max)
            {
                GameObject.Instantiate(gameObject, transform.position, transform.rotation);
                already = true;
            }
        }
    }
}
