Search Unity

Check which objects are Active/Inactive and store then in an array

Discussion in 'Scripting' started by brut69, Aug 20, 2017.

  1. brut69

    brut69

    Joined:
    Jul 8, 2017
    Posts:
    10
    I am working with a Save feature for my game. In order for it to work I am need to save the status of all the objects in the game. Luckily for me this has to be done only once (after player clicks Save) during Save and once more during Load so it can set the objects to their correct status (Active or Inactive)

    So far I found this :

    Code (CSharp):
    1.     using UnityEngine;
    2.     using System.Collections;
    3.    
    4.     public class CheckIt : MonoBehaviour {
    5.    
    6.         public GameObjScript[] gameObjArray;
    7.    
    8.         public void Start()
    9.         {
    10.             PopulateGameObjArray();
    11.         }
    12.    
    13.         void PopulateGameObjArray()
    14.         {
    15.             gameObjArray = GetComponentsInChildren<GameObjScript>();
    16.         }
    17.    
    18.         public void CheckObjStatus()
    19.         {
    20.             if(AreAllGameObjInactive())
    21.             {
    22.                 print ("All are inactive? Do something!");
    23.             }
    24.             else
    25.             {
    26.                 print ("one of the object is active");
    27.             }
    28.         }
    29.    
    30.         bool AreAllGameObjInactive()
    31.         {
    32.             foreach(GameObjScript gameObj in gameObjArray)
    33.             {
    34.                 if(gameObj.gameObject.activeInHierarchy)
    35.                 {
    36.                     return false;
    37.                 }
    38.             }
    39.             return true;
    40.         }
    41.     }
    42.  
    and attaching this to the objects that need checking:

    Code (CSharp):
    1.     using UnityEngine;
    2.     using System.Collections;
    3.    
    4.     public class GameObjScript : MonoBehaviour
    5.     {
    6.    
    7.         CheckIt parentScript;
    8.    
    9.         void Awake()
    10.         {
    11.             parentScript = transform.GetComponentInParent<CheckIt>();
    12.         }
    13.    
    14.         void OnDisable()
    15.         {
    16.             parentScript.CheckObjStatus();
    17.         }
    18.     }
    19.  
    Source : https://forum.unity3d.com/threads/check-if-multiple-gameobjects-are-active.277411/

    Which is a smart way of doing the first part of what I want ... but I can't for the life of me change it so that it stores the active objects in one array and the inactive in another.

    Any ideas how to modify the script?
     
  2. brut69

    brut69

    Joined:
    Jul 8, 2017
    Posts:
    10
    Thank you , I will try it and let you know