Hej, jeg er gået igang med lidt unity efter en meget lang C# pause.
jeg ville lave sådan man spawner et random sted (ud fra de spwans der er placeret i mappet)
jeg har prøvet med det her:
- public void spawn()
- {
- if(spawned)
- {
- Destroy(curentPlayer);
- spawned = false;
- }
- System.Random rand = new System.Random();
- GameObject[] spawn = GameObject.FindGameObjectsWithTag("spawn");
- int spawns = spawn.Length;
- if(spawns == 0)
- {
- ErrorManager.addError("No spawn points in this map");
- }
-
- int random = rand.Next(0, spawns-1);
- GameObject randomSpawn = spawn[random];
- curentPlayer = Instantiate(playerPrefab, randomSpawn.transform.position, Quaternion.identity);
- spawned = true;
- }
virker helt perfekt, men har lagt mærke til jeg ALDRIG spawner det ene sted.
så prøvet det her stump kode for at se hvor random det faktisk var.
- void randTest()
- {
- System.Random rand = new System.Random();
- int[] res = new int[3];
- for(int i=0; i<1000; i++)
- {
- int r = rand.Next(0, 2);
- res[r]++;
- }
-
- Debug.Log(res[0]);
- Debug.Log(res[1]);
- Debug.Log(res[2]);
- }
output
492
UnityEngine.Debug:Log(Object)
player:randTest() (at Assets/Scripts/player.cs:49)
player:Start() (at Assets/Scripts/player.cs:17)
508
UnityEngine.Debug:Log(Object)
player:randTest() (at Assets/Scripts/player.cs:50)
player:Start() (at Assets/Scripts/player.cs:17)
0
UnityEngine.Debug:Log(Object)
player:randTest() (at Assets/Scripts/player.cs:51)
player:Start() (at Assets/Scripts/player.cs:17)
så 3 forkommer aldrig, nogen bud på hvorfor?
Next(Int32, Int32) Returns a random number within a specified range.
http://msdn.microsoft.com/en-us/library/system.random.aspxhele klassen er her:
- using UnityEngine;
- using System.Collections;
-
- public class player : MonoBehaviour
- {
-
- public GameObject playerPrefab;
- private Object curentPlayer;
- private bool spawned = false;
-
- // Use this for initialization
- void Start ()
- {
-
- //Spawn player
- spawn();
-
- randTest();
-
- }
-
- public void spawn()
- {
- if(spawned)
- {
- Destroy(curentPlayer);
- spawned = false;
- }
- System.Random rand = new System.Random();
- GameObject[] spawn = GameObject.FindGameObjectsWithTag("spawn");
- int spawns = spawn.Length;
- if(spawns == 0)
- {
- ErrorManager.addError("No spawn points in the map");
- }
-
- int random = rand.Next(0, spawns-1);
- GameObject randomSpawn = spawn[random];
- curentPlayer = Instantiate(playerPrefab, randomSpawn.transform.position, Quaternion.identity);
- spawned = true;
- }
-
-
- void randTest()
- {
- System.Random rand = new System.Random();
- int[] res = new int[3];
- for(int i=0; i<1000; i++)
- {
- int r = rand.Next(0, 2);
- res[r]++;
- }
-
- Debug.Log(res[0]);
- Debug.Log(res[1]);
- Debug.Log(res[2]);
- }
-
- }
Indlæg senest redigeret d. 28.02.2013 15:10 af Bruger #3427