Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

carousel script c# for unity3d

Discussion in 'Scripting' started by Wixar172, May 13, 2016.

  1. Wixar172

    Wixar172

    Joined:
    May 6, 2016
    Posts:
    14
    Hello guys, i just wanted to share this script with you, it creates a carousel with game objects, hopefully it might help someone save some time, i tried to document it as best as possible.
    you can download the script, or the test project(created with unity 5.3.2) i included it at the bottom.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. //Wissam El Hajj, 2016
    5. //this is a simple script that creates a carousel form game objects
    6. //this script is provided as is without any guarentees
    7. /*
    8. * to use this script just place it on any gameobject in the scene, this element shouldn't have a collider so an empty game object is ideal
    9. * add elements to the carouselObjects array, make sure these items have a collider
    10. * make sure there are no elements with colliders in between the center and the carousel elements
    11. */
    12. public class CreateCarousel : MonoBehaviour {
    13.  
    14.     public GameObject[] carouselObjects;//the elements of the carousel
    15.     public bool ResetCenterRotation = true;//do you want to reset the rotation of the carousel center (recommended to be true)
    16.     public float DistanceFromCenter = 10.0f;//the distance from the center of the carousel
    17.     public bool AssumeObject = true; // if true assume the object that is picked, otherwise (false) keep checking what the next item is through raycast.
    18.     public int ChosenObject = 0; //index of the object that is centered in the carousel
    19.     public float speedOfrotation = 0.1f; //the speed in which the carousel rotates: values should be between 0.01f -> 1.0f, zero will stop the rotation
    20.  
    21.  
    22.     private static float diameter = 360.0f; //the diameter is always 360 degrees
    23.     private Transform theRayCaster = null; //create an empty transform
    24.     private float Angle = 0.0f; //the angle for each object in the carousel
    25.     private float newAngle = 0.0f; //the calculated angle
    26.     private bool firstTime = true; //used to calculate the offset for the first time
    27.  
    28.  
    29.     void Start ()
    30.     {
    31.         Debug.Log(carouselObjects[0].name);//just display the name of the first chosen element in the console
    32.         GameObject raycastHolder = new GameObject ();//create an empty gameobject
    33.         raycastHolder.name = "RaycastPicker"; //rename it to RaycastPicker
    34.         theRayCaster = raycastHolder.transform; // assign the transform of the newlycreated gameobject to the raycast transform variable
    35.         theRayCaster.position = transform.position; // place it at the positon of the carousel center
    36.         if (ResetCenterRotation) {
    37.             transform.rotation = Quaternion.identity;//reset the rotation of the carousel center
    38.         }
    39.  
    40.         Angle = diameter / (float)carouselObjects.Length;//calculate the angle according to the number of elements
    41.         float ObjectAngle = Angle;//create a temp value that keeps track of the angle of each element
    42.         for (int i = 0; i < carouselObjects.Length; i++) { //loop through the objects
    43.            
    44.             carouselObjects [i].transform.position = this.transform.position;//Reset objects to the postion of the carousel center
    45.             carouselObjects [i].transform.rotation = Quaternion.identity; //make sure their rotation is zero
    46.             carouselObjects [i].transform.parent = this.transform; // make the element child to the carousel center
    47.             carouselObjects [i].transform.position = new Vector3 (this.transform.position.x, this.transform.position.y, this.transform.position.z + DistanceFromCenter);//move each carousel item from the center an amount of "DistanceFromCenter"
    48.             carouselObjects [i].transform.RotateAround (this.transform.position, new Vector3 (0, 1, 0), ObjectAngle);//position the element in their respective locations accordind to the center throufh rotation
    49.             ObjectAngle += Angle;//calculate the next angle value
    50.         }
    51.  
    52.         //Make sure an element is perfectly centered.
    53.         if (carouselObjects.Length % 2 != 0) {
    54.             float rotateAngle = Angle + Angle / 2;
    55.             transform.eulerAngles = new Vector3 (transform.eulerAngles.x, rotateAngle, transform.eulerAngles.z);
    56.             newAngle = rotateAngle;
    57.         }
    58.         else
    59.         {
    60.             transform.eulerAngles = new Vector3 (transform.eulerAngles.x, Angle, transform.eulerAngles.z);
    61.             newAngle = Angle;
    62.         }
    63.  
    64.         ////////////////////////////////////////////////////////////////////////////////////////////////////////
    65.         /// ////////////////////////////////////////////////////////////////////////////////////////////////////
    66.         /// Correct the carrousel and make sure the first item in the array is the first element in the carousel
    67.         ///
    68.         theRayCaster.position = transform.position;
    69.         string objectName = "";
    70.         RaycastHit hit;
    71.         if (Physics.Raycast(transform.position, -theRayCaster.forward, out hit, DistanceFromCenter ))
    72.         {
    73.             objectName = hit.collider.name;
    74.         }
    75.  
    76.         if (objectName != carouselObjects [0].name) // only work if the first item presented isn't the first item in the array
    77.         {
    78.             for (int c = 0; c < carouselObjects.Length; c++) //loop through the array
    79.             {
    80.                 if (carouselObjects [c].name == objectName)
    81.                 {
    82.                     float angleMultiplier = c++; //the array starts with zero so adding 1 to c gives the correct value
    83.                     transform.eulerAngles = new Vector3 (transform.eulerAngles.x, transform.eulerAngles.y + Angle * angleMultiplier, transform.eulerAngles.z); //rotate the carousel to center the first object in the array
    84.                     newAngle = transform.eulerAngles.y; //reset the angle to the newly calculated angle
    85.  
    86.                     break; //exit the loop so it won't do any unecessary calculations
    87.                 }
    88.             }
    89.         }
    90.        ////////////////////////////////////////////////////////////////////////////////////////////////////////
    91.     }
    92.    
    93.     // Update is called once per frame
    94.     void Update ()
    95.     {
    96.         if (AssumeObject == false)
    97.         {
    98.             // use raycast to dynamically check which item is selected not recommended unless necessary
    99.             theRayCaster.position = transform.position;
    100.             RaycastHit hit;
    101.             if (Physics.Raycast (transform.position, -theRayCaster.forward, out hit, DistanceFromCenter)) {
    102.                 Debug.Log (hit.collider.name);//display in the console which element is detected
    103.             }
    104.         }
    105.  
    106.             Quaternion newRotation = Quaternion.AngleAxis (newAngle, Vector3.up); // pick the rotation axis and angle
    107.             transform.rotation = Quaternion.Slerp (transform.rotation, newRotation, speedOfrotation);  //animate the carousel
    108.        
    109.     }
    110.  
    111.     public void rotateTheCarouselLeft() // call this function to rotate the carousel towards the left
    112.     {
    113.         if (firstTime)// if run the first time calcule the offset
    114.         {
    115.             newAngle = transform.eulerAngles.y;
    116.             newAngle += Angle;
    117.             firstTime = false; // stop this piece of code from running in the future
    118.         }
    119.         else
    120.         {
    121.             newAngle += Angle; //calculate the new angle
    122.         }
    123.         if (AssumeObject == true)//here we check which element is selected and if we reached the start of the array we reset the index
    124.         {
    125.             if (ChosenObject <= 0) {
    126.                 ChosenObject = carouselObjects.Length - 1;
    127.             } else {
    128.                 ChosenObject--;
    129.             }
    130.             Debug.Log(carouselObjects[ChosenObject].name); //show in the console the name of the selected element
    131.         }
    132.     }
    133.     public void rotateTheCarouselRight()// call this function to rotate the carousel towards the right
    134.     {
    135.         if (firstTime) // if run the first time calcule the offset
    136.         {
    137.             newAngle = transform.eulerAngles.y;
    138.             newAngle -= Angle;
    139.             firstTime = false; // stop this piece of code from running in the future
    140.         }
    141.         else
    142.         {
    143.             newAngle -= Angle; //calculate the new angle
    144.         }
    145.         if (AssumeObject == true) //here we check which element is selected and if we reached the end of the array we reset the index
    146.         {
    147.             if (ChosenObject >= carouselObjects.Length-1) {
    148.                 ChosenObject = 0;
    149.             } else {
    150.                 ChosenObject++;
    151.             }
    152.             Debug.Log(carouselObjects[ChosenObject].name); //show in the console the name of the selected element
    153.         }
    154.     }
    155. }
     

    Attached Files:

    Rodolinc likes this.
  2. Rodolinc

    Rodolinc

    Joined:
    Sep 23, 2013
    Posts:
    63
    Hey man! THANK YOU for sharing this, I hope you have a nice day!
     
  3. Wixar172

    Wixar172

    Joined:
    May 6, 2016
    Posts:
    14
    no prob man
     
  4. immacul8_apps

    immacul8_apps

    Joined:
    Apr 4, 2015
    Posts:
    9
    I tried this code and your example and when I click the rotate button the white cube just creates a white trail and the whole screen becomes white. doesn't just rotate to next cube.
    Do you have update for this or know how to fix this.

    Thanks
     
  5. larku

    larku

    Joined:
    Mar 14, 2013
    Posts:
    1,422
    I've never used this script, but that sounds list a camera clear flags issue (??)
     
  6. Wixar172

    Wixar172

    Joined:
    May 6, 2016
    Posts:
    14
    just like larku said its a clear flag issue, not the script. on your camera, click on clear flags, and choose either skybox or solid color, you can also get away with other options if you have another camera that renders a background
     
  7. Deleted User

    Deleted User

    Guest

    Hi, I tried to apply this code. So I created an empty gameobject, attached your script and put my buttons in your array of gameobjects. The problem is that when I run the code my buttons just get deleted from the scene. How do I fix that?
     
  8. Wixar172

    Wixar172

    Joined:
    May 6, 2016
    Posts:
    14
    this code is meant to be used with 3d objects and not UI elements like buttons
     
  9. Qryche

    Qryche

    Joined:
    Aug 1, 2017
    Posts:
    1
    Hey man, great script! Just ran across this earlier today. Works great. Once I looked at your test project, it all made sense. Saved me a bunch of time, thanks again.
     
  10. ghubert_twin

    ghubert_twin

    Joined:
    Jun 18, 2019
    Posts:
    4
    2019 and still usefull, thanks a lot !
     
  11. SimbaKhan

    SimbaKhan

    Joined:
    Nov 10, 2019
    Posts:
    1
    hi there. thanks for sharing. My question is how could we bring selected game object or 3d character on zero index or starting point on focus. Because it always started from zero index.
     
  12. PanderaStudios

    PanderaStudios

    Joined:
    May 27, 2017
    Posts:
    4
    thanks a lot!