Happy_Forest/Assets/Scripts/PilleSpawnerWithPrefab.cs

111 lines
3.3 KiB
C#

using System.Collections;
using Unity.Entities;
using Unity.Mathematics;
using UnityEngine;
namespace HappyForest.Prototypen
{
public class PilleSpawnerWithPrefab : MonoBehaviour
{
[SerializeField] private GameObject pillePrefab;
private int pilleCount = 0;
private float lastSpawnTime = 0f;
private float spawnDelay = 0.05f;
private Transform pilleContainer;
void Start()
{
if (pillePrefab == null)
{
Debug.LogError("❌ Pille Prefab nicht zugewiesen!");
return;
}
pilleContainer = new GameObject("PilleInstances").transform;
}
void Update()
{
if (Time.time - lastSpawnTime < spawnDelay)
return;
if (Input.GetKey(KeyCode.Space))
{
SpawnPille();
lastSpawnTime = Time.time;
}
if (Input.GetKey(KeyCode.M))
{
DeleteRandomPille();
lastSpawnTime = Time.time;
}
if (Input.GetKey(KeyCode.C))
{
// Spawn 100 Pillen mit Delay, jede bei einer anderen Pille
StartCoroutine(SpawnMultiplePillen(100));
lastSpawnTime = Time.time;
}
}
void SpawnPille()
{
if (pillePrefab == null)
return;
// Zufällige horizontale Richtung
var random = new Unity.Mathematics.Random((uint)System.Guid.NewGuid().GetHashCode());
float angle = random.NextFloat() * math.PI * 2;
var velocity = new Vector3(math.cos(angle), 0, math.sin(angle));
// Spawn-Position: Bei einer existierenden Pille oder Default
Vector3 spawnPos = new Vector3(0, 5, 0);
if (pilleContainer.childCount > 0)
{
// Wähle zufällige existierende Pille
int randomIndex = UnityEngine.Random.Range(0, pilleContainer.childCount);
Transform randomPille = pilleContainer.GetChild(randomIndex);
spawnPos = randomPille.position;
}
// Instantiiere Prefab
var pilleGO = Instantiate(pillePrefab, pilleContainer);
pilleGO.name = $"Pille_{pilleCount}";
pilleGO.transform.position = spawnPos;
// Füge MovementScript hinzu
var mover = pilleGO.AddComponent<PilleGameObjectMover>();
mover.velocity = velocity.normalized * 5f;
pilleCount++;
}
void DeleteRandomPille()
{
if (pilleContainer.childCount > 0)
{
Destroy(pilleContainer.GetChild(0).gameObject);
pilleCount--;
}
}
IEnumerator SpawnMultiplePillen(int count)
{
for (int i = 0; i < count; i++)
{
SpawnPille();
yield return new WaitForSeconds(0.01f);
}
}
void OnGUI()
{
GUI.color = Color.yellow;
GUI.skin.label.fontSize = 20;
GUI.Label(new Rect(10, 10, 400, 30), $"Pillen: {pilleCount} | FPS: {(int)(1f / Time.deltaTime)}");
GUI.Label(new Rect(10, 50, 400, 30), "Space=Spawn | M=Delete | C=Spawn100");
}
}
}