Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

I want spawner not working while invisible.

Discussion in 'Scripting' started by S2ciForewer, Oct 19, 2020.

  1. S2ciForewer

    S2ciForewer

    Joined:
    Dec 2, 2019
    Posts:
    2
    Hello Guys.
    My problem is; I have a spawner and I want this spawner not working while invisible. But After invisible will work. But codes not working pls help me.

    Code (CSharp):
    1. public class HazardSpawner : MonoBehaviour
    2. {
    3.     [SerializeField] GameObject hazardGameObject;
    4.     Renderer m_Renderer;
    5.  
    6.     bool spawn = true;
    7.  
    8.     void Start()
    9.     {
    10.          m_Renderer = GetComponent<Renderer>();
    11.             StartCoroutine(HazSpawner());
    12.     }
    13.  
    14.     void Update()
    15.     {
    16.         HazSpawner();
    17.     }
    18.  
    19.  
    20.     IEnumerator HazSpawner()
    21.     {
    22.  
    23.         if (m_Renderer.isVisible)
    24.         {
    25.             while (spawn)
    26.             {
    27.  
    28.                 yield return new WaitForSeconds(Random.Range(1f, 2f));
    29.                 Instantiate(hazardGameObject, transform.position, Quaternion.identity);
    30.  
    31.             }
    32.         }
    33.            
    34.                  
    35.     }
    36.  
    37.    
    38.     private void OnBecameVisible()
    39.     {
    40.         enabled = true;
    41.     }
    42.     private void OnBecameInvisible()
    43.     {
    44.  
    45.         enabled = false;
    46.     }
    47.  
    48. }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,923
    Change this:
    Code (CSharp):
    1. if (m_Renderer.isVisible)
    2. {
    3.     while (spawn)
    4.     {
    5.         yield return new WaitForSeconds(Random.Range(1f, 2f));
    6.         Instantiate(hazardGameObject, transform.position, Quaternion.identity);
    7.     }
    8. }
    to this:
    Code (CSharp):
    1. while (spawn)
    2. {
    3.     if (m_Renderer.isVisible)
    4.     {
    5.         yield return new WaitForSeconds(Random.Range(1f, 2f));
    6.         Instantiate(hazardGameObject, transform.position, Quaternion.identity);
    7.     }
    8.     else {
    9.         yield return null;
    10.     }
    11. }