- Home /
Question by
Chocolade · Nov 29, 2017 at 08:16 PM ·
c#scripting problemscript.
How can i pick two randomly items from gameobject array ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class Test : MonoBehaviour
{
private GameObject[] wallsParents = new GameObject[4];
// Use this for initialization
void Start ()
{
wallsParents[0] = GameObject.Find("Top Wall");
wallsParents[1] = GameObject.Find("Left Wall");
wallsParents[2] = GameObject.Find("Right Wall");
wallsParents[3] = GameObject.Find("Bottom Wall");
System.Random rnd = new System.Random();
var res = wallsParents.OrderBy(x => rnd.Next()).Take(2);
}
// Update is called once per frame
void Update ()
{
}
}
I have 4 walls in the array wallsParents and i want to pick two walls from the array fro example wallsParents[0] and wallsParents[3] or wallsParents[2] and wallsParents[1] any two random walls and not the same so there will be no wallsParents[0] and wallsParents[0]
So in the end i will have a new array or List with two walls.
And if what i did is good var res = wallsParents.OrderBy(x => rnd.Next()).Take(2); then how later i'm getting the two picked random items from the variable res ?
Comment
Best Answer
Answer by mafima · Nov 29, 2017 at 08:29 PM
List<GameObject> walllist;
void Start(){
wallsParents[0] = GameObject.Find("Top Wall");
wallsParents[1] = GameObject.Find("Left Wall");
wallsParents[2] = GameObject.Find("Right Wall");
wallsParents[3] = GameObject.Find("Bottom Wall");
// populate list
foreach(GameObject g in wallsParents) {
walllist.Add(g);
}
// remove random 2 times
for(int i=0;i<2;i++){
walllist.Remove(walllist[Random.Range(0,walllist.Count)]);
}
// you end up with a list that has 2 random gameobjects
}