Search Unity

Add objects to list automatically

Discussion in 'Scripting' started by MoreThanWinner, Sep 25, 2018.

  1. MoreThanWinner

    MoreThanWinner

    Joined:
    Jul 27, 2018
    Posts:
    19
    I'm building a board game with quizzes. The problem is: now I have 2 Quiz cameras for testing. After the player gets one of them right, it switches back to the MainCamera, ok. But after it gets the answer only the camera gets destroyed. How do I destroy the random camera it picked + the rest of the quiz?
    I think the way is creating a list of objects that will be destroyed... but how??
    Code (CSharp):
    1. {
    2.  
    3.     public void ButtonReturnToMainCamera()
    4.     {
    5.         if (m_canSwitchBack)
    6.         {   // Swap back.
    7.             m_camMain.enabled = true;
    8.             m_camTemp.enabled = false;
    9.             m_canSwitchBack = false;
    10.             Destroy(m_camTemp.gameObject);
    11.         }
    12.     }
    13.     void Start()
    14.     {
    15.         m_camMain = Camera.main;
    16.         foreach (var cam in camerasList)
    17.             cam.enabled = false;
    18.     }
    19.     void OnTriggerEnter2D(Collider2D collision)
    20.     {
    21.         if (collision.CompareTag(m_player)
    22.             && m_triggered == null)
    23.         {
    24.             m_triggered = StartCoroutine(EnableRandom());
    25.         }
    26.     }
    27.     IEnumerator EnableRandom()
    28.     {
    29.         yield return new WaitForSeconds(2f);
    30.         if (camerasList.Count != 0)
    31.         {
    32.             // Let's pick our random camera.
    33.             var randomInt = Random.Range(0, camerasList.Count);
    34.             m_camTemp = camerasList[randomInt];
    35.             camerasList.RemoveAt(randomInt);
    36.             // Swap over.
    37.             m_camMain.enabled = false;
    38.             m_camTemp.enabled = true;
    39.             m_canSwitchBack = true;
    40.             m_triggered = null;
    41.             // Create list and destroy the quiz      
    42.          
    43.         }
    44.     }
    45.     const string m_player = "Player";
    46.     [SerializeField] List<Camera> camerasList;
    47.     Camera m_camMain;
    48.     Camera m_camTemp;
    49.     Coroutine m_triggered;
    50.     bool m_canSwitchBack;
    51. }
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    MoreThanWinner likes this.
  3. MoreThanWinner

    MoreThanWinner

    Joined:
    Jul 27, 2018
    Posts:
    19