- Home /
 
How to get all gameObjects with a script on them
I want all my images on a canvas to rotate 180 degrees when the turn ends but I dont want to choose what cards chnage based on Tags because I needs those for later use, I put a script on all the cards called "PlayingCard" and this is my script currently:
public class EndTurn : MonoBehaviour { // public PlayingCard[] GameCards;
 private void Start()
 {
    
 } 
 
 private void Update()
 {
     //GameCards = GetComponentsInChildren<RectTransform>();
 }
 private void OnGUI()
 {
     if (GUI.Button(new Rect(650, 10, 100, 20), "End Turn"))
     {
         PlayingCard[] GameCards = FindObjectsOfType(typeof(PlayingCard)) as PlayingCard[];
         foreach (PlayingCard component in GameCards)
         {
            // RectTransform rectTransform = GetComponent<RectTransform>();
             transform.Rotate(new Vector3(0, 0, 45));
         }
     }
 }
 
               }
Answer by Kabaw · May 01, 2018 at 05:39 PM
Hi @ZachBoi ,
To get all gameObjects with a specifc script on them you can use the method Object.FindObjectsOfType
Exemple:
 PlayingCard[] playingCardArray  = Object.FindObjectsOfType<PlayingCard>();
 
               After that you can accesse the GameObjects via:
 playingCardArray[index].gameObject
 
               
 But keep in mind that Object.FindObjectsOfType is a very slow function. So calling it many times per frame is not a good ideia. If you need to do this more frequently, I would recomend you to create a singleton controller script with a list of PlayingCard, and then have each new instance of PlayingCard putting their own reference in the controller's list.
I don't get where/how to reference it in the foreach function with the script you made (also thank you).
Your answer