Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

how to enable (disabled) spawner?

Discussion in 'Scripting' started by karammaks, May 23, 2014.

  1. karammaks

    karammaks

    Joined:
    Apr 6, 2014
    Posts:
    146
    Hi

    i have a game , if the user reached specific number of score for example if player reached 100 score , an exist( disabled spawner from inspector ) will be enabled , would you please tell me how to do so ? :confused:
     
  2. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    There's a different between a MonoBehaviour being enabled, and a GameObject being active.

    The first step is getting a reference to the spawner. Then either activating it's gameObject or enabling the MonoBehaviour.

    Without seeing your relevant code, here's an example I made up.
    Code (csharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public class User : MonoBehaviour {
    5.   // Assign in inspector
    6.   public Spawner m_spawner;
    7.  
    8.   public AwardScore(int points) {
    9.     score += points;
    10.     if (score >= 100) {
    11.       m_spawner.gameObject.SetActive(true);
    12.       m_spawner.enabled = true;
    13.     }
    14.   }
    15.  
    16.   int score { get; set; }
    17. }
    18.  
     
  3. karammaks

    karammaks

    Joined:
    Apr 6, 2014
    Posts:
    146
    i have multible of spawners which each one has its own class with its own behavior and codes, so how to activate one of them ??
     
  4. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    You have to find the spawner you want.

    I suggest making a SpawnerManager to track each spawner and let you access the one you want. If you have something initializing the scene, it can pass the SpawnerManager to whatever script needs it. You can also make it a singleton.

    Otherwise, here is a way to do it using a Find command, just don't use any of the Find commands every frame. This command only works on ACTIVE game objects, so find the objects before they're deactivated if they are getting deactivated. I assume it'll find disabled Monobehaviours, though I'm not 100% sure on that.

    Code (csharp):
    1.  
    2. Spawner[] allSpawners;
    3.  
    4. Spawner FindSpawner() {
    5.   // Only finds ACTIVE gameobjects.
    6.   allSpawners = Object.FindObjectsOfType(typeof(Spawner)) as Spawner[];
    7. }
    8.  
    9. void ActivateSpawner() {
    10.   foreach (Spawner s in allActiveSpawners) {
    11.     // psuedo code. You'll have to figure out which one you want.
    12.     if (s is the spawner we want) {
    13.       s.enabled = true;
    14.     }
    15.   }
    16. }
    17.  
     
  5. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,523