Skip to content

Instantly share code, notes, and snippets.

@TheStoneBook
Last active June 23, 2018 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheStoneBook/0154a6d848a5940eb901cbc93a4828c0 to your computer and use it in GitHub Desktop.
Save TheStoneBook/0154a6d848a5940eb901cbc93a4828c0 to your computer and use it in GitHub Desktop.
【Unity】配列のシャッフル
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