using UnityEngine; public class RandomSpawner : MonoBehaviour { [Header("Player Reference")] public GameObject player; [Header("Spawn Points")] public Transform[] spawnPoints; void Start() { SpawnPlayerAtRandomPoint(); } public void SpawnPlayerAtRandomPoint() { if (spawnPoints.Length == 0 || player == null) { Debug.LogWarning("กรุณาใส่ Player และ Spawn Points ใน Inspector ให้ครบถ้วน!"); return; } // อ่าน Index ของจุดเกิดรอบล่าสุดที่เคยบันทึกไว้ (ค่าเริ่มต้นคือ -1) int lastSpawnIndex = PlayerPrefs.GetInt("LastSpawnIndex", -1); int randomIndex = lastSpawnIndex; // ถ้ามีจุดเกิดมากกว่า 1 จุด ให้สุ่มวนลูปหาจุดที่ไม่ซ้ำกับรอบล่าสุด if (spawnPoints.Length > 1) { while (randomIndex == lastSpawnIndex) { randomIndex = Random.Range(0, spawnPoints.Length); } } else { randomIndex = 0; } // บันทึก Index ของจุดเกิดรอบนี้ไว้ใช้เช็กในรอบถัดไป PlayerPrefs.SetInt("LastSpawnIndex", randomIndex); PlayerPrefs.Save(); Transform selectedPoint = spawnPoints[randomIndex]; // ปิด CharacterController ชั่วคราวก่อนย้ายตำแหน่ง CharacterController controller = player.GetComponent(); if (controller != null) { controller.enabled = false; } // ย้ายตำแหน่งและทิศทาง player.transform.position = selectedPoint.position; player.transform.rotation = selectedPoint.rotation; // เปิด CharacterController กลับมาใช้งาน if (controller != null) { controller.enabled = true; } Debug.Log("Player เกิดที่จุด: " + selectedPoint.name + " (Index: " + randomIndex + ")"); } }