Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Random game object reshuffling.

Discussion in 'Scripting' started by Awesomevk47, Dec 30, 2017.

  1. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    So i have 10 game objects.. (cubes)...and I want them to randomly reshuffle positions among themselves after an interval of every 120seconds (2 minutes)...what do I do please help.
     
    DAIMULAR likes this.
  2. hasanbayat

    hasanbayat

    Joined:
    Oct 18, 2016
    Posts:
    626
    Easily, Shuffle them that means swap source to destination, loop through the 10 game objects and generate a destination index and swap the destination game object with the current game object:
    Code (CSharp):
    1. public static void Shuffle (GameObject[] gameObjects) {
    2.     for (int i = 0; i < gameObjects.Length; i++) {
    3.  
    4.         // Find a random index
    5.         int destIndex = Random.Range (0, gameObjects.Length);
    6.         GameObject source = gameObjects[i];
    7.         GameObject dest = gameObjects[destIndex];
    8.  
    9.         // If is not identical
    10.         if (source != dest) {
    11.  
    12.             // Swap the position
    13.             source.transform.position = dest.transform.position;
    14.  
    15.             // Swap the array item
    16.             gameObjects[i] = gameObjects[destIndex];
    17.         }
    18.     }
    19. }
    Thanks.
     
    Awesomevk47 likes this.
  3. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    Ok since I am a programming noob a bit of explanation would be highly appreciated.
     
  4. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    my cubes are named as cube1 cube2 etc
     
  5. hasanbayat

    hasanbayat

    Joined:
    Oct 18, 2016
    Posts:
    626
    Create an Array of Cubes and use the function to shuffle them and their position.

    Thanks.
     
  6. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    How do i make the cubes reshuffle every 120 seconds.....thanks
     
  7. hasanbayat

    hasanbayat

    Joined:
    Oct 18, 2016
    Posts:
    626
    Use a Coroutine, or do it in a Update method, by Coroutine:
    Code (CSharp):
    1. void Start () {
    2.     StartCoroutine ("WaitAndShuffle");
    3. }
    4.  
    5. IEnumerator WaitAndShuffle () {
    6.     while (true) {
    7.         yield return new WaitForSeconds (120);
    8.         Shuffle (cubes);
    9.     }
    10. }
     
    Awesomevk47 likes this.
  8. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    Thanks a lot for your support ....but please answer another question where should i apply this Coroutine script...thnks a ton
     
  9. hasanbayat

    hasanbayat

    Joined:
    Oct 18, 2016
    Posts:
    626
    You need to apply the functions to where you have cubes and manage them, the MonoBehaviour script.

    Thanks.
     
  10. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    oK so i am using this script



    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class shuffle : MonoBehaviour {
    public GameObject[] Cube;

    public static void Shuffle (GameObject[] gameObjects) {
    for (int i = 0; i < gameObjects.Length; i++) {

    // Find a random index
    int destIndex = Random.Range (0, gameObjects.Length);
    GameObject source = gameObjects;
    GameObject dest = gameObjects[destIndex];

    // If is not identical
    if (source != dest) {

    // Swap the position
    source.transform.position = dest.transform.position;

    // Swap the array item
    gameObjects = gameObjects[destIndex];
    }
    }
    }



    but i am getting compiler errors please help
     

    Attached Files:

  11. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
  12. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    okokok sorry i fixed the compiler errors
     
  13. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    ok i fixed the compiler errors.....but could not get the cubes shuffling randomly.....whenever i hit the play button.....the cubes do not reshuffle pls help


    code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Randomshuffle : MonoBehaviour {
    6.     public GameObject[] cube;
    7.  
    8.     public static void Shuffle (GameObject[] gameObjects) {
    9.         for (int i = 0; i < gameObjects.Length; i++) {
    10.  
    11.             // Find a random index
    12.             int destIndex = Random.Range (0, gameObjects.Length);
    13.             GameObject source = gameObjects[i];
    14.             GameObject dest = gameObjects[destIndex];
    15.  
    16.             // If is not identical
    17.             if (source != dest) {
    18.  
    19.                 // Swap the position
    20.                 source.transform.position = dest.transform.position;
    21.  
    22.                 // Swap the array item
    23.                 gameObjects[i] = gameObjects[destIndex];
    24.             }
    25.         }
    26.     }
    27.     // Use this for initialization
    28.     void Start () {
    29.  
    30.     }
    31.  
    32.     // Update is called once per frame
    33.     void Update () {
    34.  
    35.     }
    36. }
    37.  
     
    dr6666 likes this.
  14. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Well, there are 2 issues I see here..
    1. is that the method is static but I imagine you want to access the cube array of game objects.
    2.. this is a big one. You haven't actually called the method! :)

    3rd issue, maybe: What happened to the timer you wanted before they shuffle? That is not here.

    You want this to happen when you start? If you got rid of the timer idea, in Start() call the method with the cube array as a parameter.
     
    cousik likes this.
  15. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    Timer comes later bro first ill try to fix this
     
  16. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Okay, well try what I wrote and see if it works ;)
     
  17. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    Since i am a newbie.....i did not understand what to do sorry for inconvenience.
     
  18. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Okay, I was suggesting that you remove the word 'static' from the method. And then in the Start() method, write "Shuffle(cube); "
     
  19. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    Ok so I replaced line "8" with: "public static void Shuffle (GameObject[] gameObjects) {"

    And in line "29" i wrote:
    "Shuffle(cube);"





    But i get a behaviour which i dont want


    In my scene i have 3 cubes (its just a test scene for my game)
    Starting from left to right
    The first cube is red second is green and the last one is blue....after applying the script whenever i hit "play" everytime a random number of cubes appear (but less than 3) sometimes 2 sometimes only one appears with any of the three colours...


    What i want is as soon as i hit "play" the number of cubes should not change but the three cubes should just interchanve their positions at random..thats it...need help please.
     
  20. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    *interchange
     
  21. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Not sure about your response, as you said you replaced the line with the exact same line..

    Anyways..let's see what we can do about the method.
    Code (csharp):
    1.  
    2. public void Shuffle (GameObject[] gameObjects) {
    3.         for (int i = 0; i < gameObjects.Length; i++) {
    4.  
    5.             // Find a random index
    6.             int destIndex = Random.Range (0, gameObjects.Length);
    7.             GameObject source = gameObjects[i];
    8.             GameObject dest = gameObjects[destIndex];
    9.   /** This could be modified to keep checking to make sure you always swap something, but leaving it for now **/
    10.             // If is not identical
    11.             if (source != dest) {
    12.  
    13.                 // Swap the positions
    14.                 Vector3 tmp = source.transform.position;
    15.                 source.transform.position = dest.transform.position;
    16.                 dest.transform.position = tmp;
    17.                  
    18.              /** I do not know what this was doing, try with it commented out! **/
    19.                 // Swap the array item
    20.               //  gameObjects[i] = gameObjects[destIndex];
    21.             }
    22.         }
    23.     }
    24. void Start() {
    25.    Shuffle(cube);
    26.   }
    27. void Update() {
    28.   if(Input.GetKeyDown(KeyCode.L)) {
    29.      Shuffle(cube);
    30.     }
    31.  }
    32.  
    Okay, try to copy & paste that and see what happens. if I made a typo, try to fix it.
    I added some code so you can type the 'L' key to run it, again. It will also run once on start.
    Let me know how that goes.
     
  22. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    I am so sorry i did not write static
     
  23. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    But i wrote a code like yours but it did not work
     
  24. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    No problem, I figured you didn't, because otherwise it would not have run :)

    Just try to paste the code I wrote and see what happens...
     
  25. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    It's working for me. Sometimes they just end up in the same spot, or only 1 moves... that's random chance.
    :)

    I just tested it in a project**
     
  26. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    Ok ill test it tomorrow. ....dont leave connection with this thread i have more problems....thanks for ur support....
     
  27. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    nods, no problem. Try the bit of code with the option to run it , again (the GetKeyDown in Update), while you test.
    Maybe then you can better see for yourself how sometimes 'x' number of them move (or not) :) Much easier, for testing, than to stop/start.. stop/start.. over n over, again. :)
     
  28. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    Since i was too lazy to type...lol..pls see this i want something like this.. 20180102_223051.jpg
     
  29. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    oh my goodness, that's some severe laziness and it's sideways lol

    All I can say , again , is try the test code and also try the Update KeyDown to test it several times during play to see the results. :) lol

    If , after that, it's still not making sense, you will have to make an effort to describe your goal a little more, because i am not seeing it very well at the moment, or when I tilt my head to read that note pad hahaha. Sorry :)
     
  30. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    ok so i pasted ur script

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Randomshuffle : MonoBehaviour {
    6.     public GameObject[] Cube;
    7.  
    8.     public void Shuffle (GameObject[] gameObjects) {
    9.         for (int i = 0; i < gameObjects.Length; i++) {
    10.  
    11.             // Find a random index
    12.             int destIndex = Random.Range (0, gameObjects.Length);
    13.             GameObject source = gameObjects[i];
    14.             GameObject dest = gameObjects[destIndex];
    15.             /** This could be modified to keep checking to make sure you always swap something, but leaving it for now **/
    16.             // If is not identical
    17.             if (source != dest) {
    18.  
    19.                 // Swap the positions
    20.                 Vector3 tmp = source.transform.position;
    21.                 source.transform.position = dest.transform.position;
    22.                 dest.transform.position = tmp;
    23.  
    24.                 /** I do not know what this was doing, try with it commented out! **/
    25.                 // Swap the array item
    26.                 gameObjects[i] = gameObjects[destIndex];
    27.             }
    28.         }
    29.     }
    30.     void Start() {
    31.         Shuffle(cube);
    32.     }
    33.     void Update() {
    34.         if(Input.GetKeyDown(KeyCode.L)) {
    35.             Shuffle(cube);
    36.         }
    37.     }





    it shows "errorCS1525 ; unexpected symbol 'end of file'
     
  31. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,378
    You're missing a closing curly bracket at the end...

    Also this:
    Code (csharp):
    1.  
    2. /** I do not know what this was doing, try with it commented out! **/
    3. // Swap the array item
    4. gameObjects[i] = gameObjects[destIndex];
    5.  
    You're supposed to be swapping the objects... but you don't have every part to it. This single line of code is just going to remove one of the GameObjects, and have the other in 2 spots.

    Do this:

    Code (csharp):
    1.  
    2. var placeHolder = gameObjects[destIndex];
    3. gameObjects[destIndex] = gameObjects[i];
    4. gameObjects[i] = placeHolder;
    5.  
    This actually swaps the 2 around so that the object at destIndex is now at i, and the one at i is not at destIndex.
     
  32. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Is that swap really necessary? I had commented the first part out, because I had added a 'swap' that wasn't in the earlier code posted by someone else. Half just wondering out loud, half asking :)
     
  33. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    umm swap is needed
     
  34. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I'm sorry that message wasn't for you, but for @lordofduct . It wasn't about needing swap in general, but that particular piece of code in his post* :)

    In my code I commented out one line that in your post wasn't commented out. So you can try that, after you add the curly brace that was giving you the error. Then, if you want, try the version that was written with the "other swap" added.. :)
     
  35. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    I have always run under the concept that if you want something shuffled, treat it like a deck of cards.... You basically have 2 stacks... 1 is the source, as you take a card randomly from stack one and add it to stack 2, remove it from stack 1.

    The best illustration is to simply create a extension class that does the work for you...

    Code (csharp):
    1.  
    2. using System.Collections.Generic;
    3. using System.Linq;
    4.  
    5. public static class Extensions{
    6.     public static List<T> Shuffle<T>(this List<T> source) {
    7.         var rtn = new List<T>();
    8.         var copy = source.ToList();
    9.         var rnd = new Random();
    10.        
    11.         while (copy.Any()) {
    12.             var index = rnd.Next(copy.Count);
    13.             rtn.Add(copy[index]);
    14.             copy.RemoveAt(index);
    15.         }
    16.  
    17.         return rtn;
    18.     }
    19.    
    20.     public static T[] Shuffle<T>(this T[] source)
    21.     {
    22.         return source.ToList().Shuffle().ToArray();
    23.     }
    24. }
    25.  
    26. //Usage:
    27.  
    28. var children = new List<Transform>();
    29. for(var i=0; i<transform.childCount; i++){
    30.     children.Add(transform.GetChild(i));
    31. }
    32.  
    33. var random = children.Shuffle();
     
    Last edited: Jan 3, 2018
  36. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I'm glad you responded & posted that. That is something I had thought of and/or read about before, and really liked, but had slipped my mind, as I was using an earlier shuffle I had grown used to. :) Cool.

    (not the exact code, but the idea of it**)
     
  37. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    Ok...so do i need to creat any array for this (i am getting a bit confused)



    Lol...confused person here
     
  38. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    Well, yes, you must create an array to start. Using just about any one of these methods, you need an initial array of objects in order to shuffle them.

    In my example, I simply pulled the array of objects from the children of the object that script would be on. So, yes, you need an array.
     
  39. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    And what is that "T"
     
  40. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    ...like we have here
     
  41. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    It means 'Type' , as the method is generic.
    You could pass List<float> or List<int> etc.. and it would work on both/either.
     
  42. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    ...
    But i want something like i have 3 cubes.....and every cube exchanges with some other cube...that is they just rearrange among themselves...but they should not intersect in their position..in oher words no two cubes should be in the same position...
     
  43. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Pretty sure if you use the code he had, you might want to add:
    Code (csharp):
    1.  
    2. Vector3 [] cubePositions;
    3. public List<Transform> cubes; // drag n drop your 3 cubes in the inspector.
    4.  
    5. void Start() {
    6.    cubePositions = new Vector3[cubes.Length];
    7.    for(int i = 0; i < cubes.Length; ++i) {
    8.        cubePositions[i] = cubes[i].position;
    9.      }
    10.    cubes = cubes.Shuffle();
    11.    for(int i = 0 ; i < cubes.Length; ++i) {
    12.        cubes[i].position = cubePositions[i];
    13.       }
    14.  }
     
  44. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    OK, positioning is then easy. After you "shuffle" them, just reset the position of each of the cubes to offset the width you need. In this case, I assume the width is 1, but you could always say... x * cubeWidth, which would be a variable defining how far apart each one should be.

    Code (csharp):
    1. for(float x=0; x<cubes.Length; x++){
    2.     cubes[x].transform.position = new Vector3(x, 0, 0);
    3. }
     
  45. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    I dont really need to reset the cube positions......
     
  46. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Not sure what you mean by that; that wasn't suggested.

    Have you tried the code that @bigmisterb posted, along with his positioning or mine?
     
  47. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    Actually sorry i have left home today afternoon.....i cant test any code for the next 5 days
     
  48. Awesomevk47

    Awesomevk47

    Joined:
    Dec 25, 2017
    Posts:
    32
    I still need help...pls dont leave this thread....
     
  49. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Sure, I only asked because I think it's going to work out nicely for you. Just write in 5 days time when you're back home & have tried it. Then follow up if anything is misunderstood or wrong then :)
     
  50. hippocoder

    hippocoder

    Digital Ape Moderator

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    But you can't code, so I'm not sure why we're helping you solve problems when you don't even want to work out that you missed a squiggly brace above.

    Why are we helping and are we actually helping? You are just sitting there asking for solution after solution. How is this helping you?