Last active
June 23, 2018 18:42
-
-
Save TheStoneBook/0154a6d848a5940eb901cbc93a4828c0 to your computer and use it in GitHub Desktop.
【Unity】配列のシャッフル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class ArrayShuffleTest : MonoBehaviour { | |
public GameObject[] Object; | |
void Start () { | |
} | |
void Update () { | |
//test | |
if (Input.GetKey (KeyCode.A)) | |
{ | |
ObjectShuffle (); | |
} | |
//test | |
if (Input.GetKey (KeyCode.B)) | |
{ | |
Object = ArrayShuffle (Object); | |
} | |
} | |
public void ObjectShuffle(){ | |
for (int i = 0; i < Object.Length; i++) { | |
GameObject tmp = Object [i]; | |
int randomIndex = Random.Range(i, Object.Length); | |
Object[i] = Object[randomIndex]; | |
Object[randomIndex] = tmp; | |
} | |
} | |
//引数ありバージョン | |
public GameObject[] ArrayShuffle(GameObject[] array) | |
{ | |
int length = array.Length; | |
GameObject[] result = new GameObject[length]; | |
array.CopyTo (result, 0); | |
for (int i = 0; i < length; i++) | |
{ | |
GameObject tmp = result [i]; | |
int randomIndex = Random.Range(i, length); | |
result[i] = result[randomIndex]; | |
result[randomIndex] = tmp; | |
} | |
return result; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment