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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Switching GameObject[] List if score >= 200? Also does this"[]" mean list or array?

Discussion in 'Getting Started' started by KUFgoddess, Dec 6, 2017.

  1. KUFgoddess

    KUFgoddess

    Joined:
    Apr 2, 2015
    Posts:
    27
    In my project I am trying to make some tiles switch to another [] of tiles if the players score is >=200.(by communicating between 2 scripts) Here's what I'm using to instantiate the tiles and this is working perfectly but now how to change its 2nd set of tiles? I keep getting a null reference error when my score reaches 200.
    1/2 Here is the Tile Manager script
    Code (CSharp):
    1.  
    2. public GameObject[] tilePrefabs;//The Default list of gameobjects.
    3.  
    4.     public GameObject[] increasedDifficultytilePrefabs;//This is the Gameobject[]list I want to switch to.
    5.  
    6.     private Transform playerTransform;
    7.     public AudioClip[] clips;
    8.     public AudioSource source;
    9.     private float spawnZ = -10.0f;
    10.     private float tileLength = 10.0f;
    11.  
    12.     private int tileAmountOnScreen = 5;
    13.     private List<GameObject> activeTiles;
    14.  
    15.     private float safeZone = 15.0f;
    16.  
    17.     private int lastPrefabIndex = 0;
    18.  
    19.     private void Start()
    20.     {
    21.         activeTiles = new List<GameObject>();
    22.         playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
    23.  
    24.         for (int i = 0; i < tileAmountOnScreen; i++)
    25.         {
    26.             if (i < 2)
    27.                 SpawnTile(0);
    28.             else
    29.                 SpawnTile();
    30.         }
    31.     }
    32.  
    33.     // Update is called once per frame
    34.     private void Update()
    35.     {
    36.         if (playerTransform.position.z - safeZone > (spawnZ - tileAmountOnScreen * tileLength))
    37.         {
    38.             SpawnTile();
    39.             RandomizeSound();
    40.             DeleteTile();
    41.         }
    42.     }
    43.  
    44.  
    45.     public void SpawnTile(int prefabIndex = -1)
    46.     {
    47.         GameObject go;
    48.         if (prefabIndex == -1)
    49.             go = Instantiate(tilePrefabs[RandomPrefabIndex()]) as GameObject;
    50.         else
    51.             go = Instantiate(tilePrefabs[prefabIndex]) as GameObject;
    52.         go.transform.SetParent(transform);
    53.         go.transform.position = Vector3.forward * spawnZ;
    54.         spawnZ += tileLength;
    55.         activeTiles.Add(go);
    56.  
    57.  
    58.     }
    59.  
    60.  
    61.     public void SpawnTile2(int prefabIndex = -1)
    62.     {
    63.         GameObject go;
    64.         if (prefabIndex == -1)
    65.             go = Instantiate(increasedDifficultytilePrefabs[RandomPrefabIndex()]) as GameObject;
    66.         else
    67.             go = Instantiate(increasedDifficultytilePrefabs[prefabIndex]) as GameObject;
    68.         go.transform.SetParent(transform);
    69.         go.transform.position = Vector3.forward * spawnZ;
    70.         spawnZ += tileLength;
    71.         activeTiles.Add(go);
    72.  
    73.  
    74.     }
    75.     void RandomizeSound()
    76.     {
    77.         source.clip = clips[Random.Range(0, clips.Length)];
    78.  
    79.     }
    80.  
    81.  
    82.     private void DeleteTile()
    83.     {
    84.         Destroy(activeTiles[0]);
    85.         activeTiles.RemoveAt(0);
    86.     }
    87.  
    88.     private int RandomPrefabIndex()
    89.     {
    90.         if (tilePrefabs.Length <= 1)
    91.             return 0;
    92.  
    93.         int randomIndex = lastPrefabIndex;
    94.         while (randomIndex == lastPrefabIndex)
    95.         {
    96.             randomIndex = Random.Range(0, tilePrefabs.Length);
    97.         }
    98.  
    99.         lastPrefabIndex = randomIndex;
    100.         return randomIndex;
    101.     }
    102.  
    103.  
    104.  
    1/2 Here is the Level Manager script
    Code (CSharp):
    1.  
    2.  
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using UnityEngine.SceneManagement;
    6. using System.Collections;
    7.  
    8. public class LevelManager : MonoBehaviour {
    9.     private float score = 0;
    10.     public Text ScoreText, StatusText;
    11.     //MUSIC
    12.  
    13.     public AudioSource levelMusic;
    14.         public AudioSource gameOverMusic;
    15.  
    16.     //ForPausingOnDeath / Respawn
    17.  
    18.     public float waitToRespawn;
    19.     public PlayerEngine thePlayer;
    20.     public GameObject DeathExplosion;
    21.  
    22.     //Coins
    23.  
    24.     public int StartLifeCount;
    25.     private int LifeBonusLifeCount;
    26.     public int bonusLifeThreshold;
    27.     public AudioSource scoreSound;
    28.  
    29.     //UI
    30.     //public Text LifeText;
    31.     public Image Life;
    32.     public Image Life2;
    33.     public Image Life3;
    34.  
    35.     public Sprite LifeFull;
    36.     public Sprite LifeHalf;
    37.     public Sprite LifeEmpty;
    38.     public int maxHealth;
    39.     public int healthCount;
    40.  
    41.     private bool respawning;
    42.  
    43.     //Array //[] square brackets mean you want to create an array
    44.     public ResetOnRespawn[] objectsToReset;
    45.  
    46.     public bool invincible;
    47.  
    48.  
    49.     public TileManager Tmanager;
    50.     //UI
    51.     //public Text livesText;
    52.     public int currentLives;
    53.     public int startingLives;
    54.  
    55.     //GameOverScreen
    56.     public GameObject gameOverScreen;
    57.  
    58.  
    59.     // Use this for initialization
    60.     void Start() {
    61.         thePlayer = FindObjectOfType<PlayerEngine>();
    62.  
    63.         //LifeText.text = "Spires x 9999" + LifeCount;
    64.         healthCount = maxHealth;
    65.  
    66.         objectsToReset = FindObjectsOfType<ResetOnRespawn>();
    67.         currentLives = startingLives;
    68.         //livesText.text = "Lives x " + currentLives;
    69.     }
    70.  
    71.     // Update is called once per frame
    72.     void Update () {
    73.         IncreaseScore(1);
    74.  
    75.         if (score >= 200)
    76.         {
    77.             Debug.Log("ChangingTileList");
    78.             Tmanager.SpawnTile2(int prefabIndex = -1);
    79.             //I want to instantiate new array here + CheckPoint Every 500 - 1000 Points?
    80.             GameObject tileObj = GameObject.Find("TileManager");
    81.             Tmanager = tileObj.GetComponent<TileManager>();
    82.  
    83.         }
    84.  
    85.  
    86.    
    87.         if (healthCount <= 0 && !respawning)
    88.         {
    89.  
    90.             //Respawn();
    91.             RestartLevel();
    92.             respawning = true;
    93.         }
    94.  
    95.         if(LifeBonusLifeCount >= bonusLifeThreshold)
    96.         {
    97.             currentLives += 1;
    98.             //livesText.text = "Lives x " + currentLives;
    99.             LifeBonusLifeCount -= bonusLifeThreshold;
    100.  
    101.         }
    102.  
    103.     }
    104.  
    105.  
    106.     public void RestartLevel()
    107.     {
    108.         StartCoroutine("WaitingDeathScreen");
    109.         //SceneManager.LoadScene("InfiniteRunner");
    110.  
    111.     }
    112.  
    113.  
    114.     public void Respawn()
    115.     {//I want my player to restart level if they dont have any lives left
    116.         currentLives -= 1;
    117.         //livesText.text = "Lives x " + currentLives;
    118.         if(currentLives > 0)
    119.         {
    120.         StartCoroutine("RespawnCo");
    121.         } else {
    122.             RestartLevel();
    123.        
    124.             thePlayer.gameObject.SetActive(false);
    125.             gameOverScreen.SetActive(true);
    126.             levelMusic.Stop();
    127.             gameOverMusic.Play();
    128.        
    129.  
    130.  
    131.             if (    Input.GetKeyDown(KeyCode.Y))
    132.             {
    133.  
    134.                 SceneManager.LoadScene("0");
    135.                 return;
    136.             }
    137.  
    138.             //levelMusic.volume = levelMusic.volume / 2f; //This is if I just want the music to turn itself down when the player dies.
    139.         }
    140.     }
    141.  
    142.  
    143.     public IEnumerator WaitingDeathScreen()
    144.  
    145.     {
    146.         thePlayer.gameObject.SetActive(false);
    147.         gameOverScreen.SetActive(true);
    148.         yield return new WaitForSeconds(6);
    149.         //gameOverScreen.SetActive(false);
    150.         yield return new WaitForSeconds(1);
    151.         SceneManager.LoadScene("InfiniteRunner");
    152.  
    153.     }
    154.     public IEnumerator RespawnCo()  //This is a corroutine//
    155.     {
    156.    
    157.  
    158.         thePlayer.gameObject.SetActive(false);
    159.         Instantiate(DeathExplosion, thePlayer.transform.position, thePlayer.transform.rotation);
    160.         yield return new WaitForSeconds(waitToRespawn);
    161.  
    162.         healthCount = maxHealth;
    163.         respawning = false;
    164.         UpdateHatMeter();
    165.  
    166.         StartLifeCount = 0;
    167.         //LifeText.text = "Drive:" + LifeCount;
    168.         LifeBonusLifeCount = 0;
    169.  
    170.  
    171.         thePlayer.transform.position = thePlayer.respawnPosition;
    172.         thePlayer.gameObject.SetActive(true);
    173.  
    174.         for(int i = 0; i < objectsToReset.Length; i++)
    175.         {
    176.  
    177.        
    178.             objectsToReset[i].gameObject.SetActive(true);
    179.             objectsToReset[i].ResetObject();
    180.         }
    181.     }
    182.  
    183.     public void AddHats(int HatsToAdd)
    184.     {
    185.         StartLifeCount += HatsToAdd;
    186.         LifeBonusLifeCount += HatsToAdd;
    187.         //LifeText.text = "Drive:" + LifeCount;
    188.         scoreSound.Play();
    189.     }
    190.  
    191.     public void HurtPlayer(int damageToTake)
    192.     {
    193.         if (!invincible)
    194.         {
    195.             healthCount -= damageToTake;
    196.             UpdateHatMeter();
    197.             //thePlayer.Knockback();
    198.             //thePlayer.hurtSound.Play();
    199.         }
    200.     }
    201.  
    202.     public void GiveHealth(int healthToGive)
    203.  
    204.     {
    205.         healthCount += healthToGive;
    206.         if(healthCount > maxHealth)
    207.         {
    208.  
    209.             healthCount = maxHealth;
    210.         }
    211.         scoreSound.Play();
    212.         UpdateHatMeter();
    213.  
    214.     }
    215.  
    216.     public void UpdateHatMeter()
    217.     {
    218.  
    219.         switch(healthCount)
    220.         {
    221.             case 6:
    222.                 Life.sprite = LifeFull;
    223.                 Life2.sprite = LifeFull;
    224.                 Life3.sprite = LifeFull;
    225.                 return;
    226.  
    227.             case 5:
    228.                 Life.sprite = LifeFull;
    229.                 Life2.sprite = LifeFull;
    230.                 Life3.sprite = LifeHalf;
    231.                 return;
    232.  
    233.             case 4:
    234.                 Life.sprite = LifeFull;
    235.                 Life2.sprite = LifeFull;
    236.                 Life3.sprite = LifeEmpty;
    237.                 return;
    238.  
    239.             case 3:
    240.                 Life.sprite = LifeFull;
    241.                 Life2.sprite = LifeHalf;
    242.                 Life3.sprite = LifeEmpty;
    243.                 return;
    244.  
    245.             case 2:
    246.                 Life.sprite = LifeFull;
    247.                 Life2.sprite = LifeEmpty;
    248.                 Life3.sprite = LifeEmpty;
    249.                 return;
    250.  
    251.             case 1:
    252.                 Life.sprite = LifeHalf;
    253.                 Life2.sprite = LifeEmpty;
    254.                 Life3.sprite = LifeEmpty;
    255.                 return;
    256.  
    257.             case 0:
    258.                 Life.sprite =  LifeEmpty;
    259.                 Life2.sprite = LifeEmpty;
    260.                 Life3.sprite = LifeEmpty;
    261.                 return;
    262.  
    263.             default:
    264.                 Life.sprite = LifeEmpty;
    265.                 Life2.sprite = LifeEmpty;
    266.                 Life3.sprite = LifeEmpty;
    267.                 return;
    268.  
    269.         }
    270.     }
    271.  
    272.     public void AddLives(int livesToAdd)
    273.     {
    274.         scoreSound.Play();
    275.         currentLives += livesToAdd;
    276.         //livesText.text = "Lives x " + currentLives;
    277.  
    278.  
    279.     }
    280.  
    281.  
    282.  
    283.     void Awake()
    284.     {
    285.         if (instance == null)
    286.         {
    287.             instance = this;
    288.         }
    289.         else
    290.         {
    291.             DestroyImmediate(this);
    292.         }
    293.     }
    294.  
    295.     //singleton implementation
    296.     private static LevelManager instance;
    297.     public static LevelManager Instance
    298.     {
    299.         get
    300.         {
    301.             if (instance == null)
    302.                 instance = new LevelManager();
    303.  
    304.             return instance;
    305.         }
    306.     }
    307.  
    308.     protected LevelManager()
    309.     {
    310.  
    311.     }
    312.  
    313.  
    314.  
    315.     public void ResetScore()
    316.     {
    317.         score = 0;
    318.         UpdateScoreText();
    319.     }
    320.  
    321.     public void SetScore(float value)
    322.     {
    323.         score = value;
    324.         UpdateScoreText();
    325.     }
    326.  
    327.     public void IncreaseScore(float value)
    328.     {
    329.         score += value;
    330.         UpdateScoreText();
    331.     }
    332.  
    333.     private void UpdateScoreText()
    334.     {
    335.         ScoreText.text = score.ToString();
    336.     }
    337.  
    338.     public void SetStatus(string text)
    339.     {
    340.         StatusText.text = text;
    341.     }
    342.  
    343.  
    344.  
    345.  
    346.  
    347.  
    348.  
    349.  
    350.  
    351.  
    352.  
    353.  
    354. }
    355.  
    356.  
    357.  
     
    Last edited: Dec 6, 2017
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Well, the best advice is to test each part to find what is null.

    Plus, you needn't write "int prefabIndex = -1" in spawn tile2. It's already the default, so you can just call SpawnTile2(); and it will be automatic. If you wanted it to be some other number, then you'd write SpawnTile(4);

    Now, you have a Tmanager which is public. Did you drag n drop this in the inspector? If so, hopefully that is set properly. There is no need to look for it again the game object, again, then get its component, again.

    Hopefully that helps. :)
     
    KUFgoddess likes this.
  3. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Oh, sorry forgot to answer the part about [] and whether it's a list or array.
    In the declaration, it always means array. However, you can index a list or array with the same syntax, eg:
    myListorArray[3] <- 4th spot in array/list (assuming it's at least 4 large ;))
     
    KUFgoddess likes this.
  4. KUFgoddess

    KUFgoddess

    Joined:
    Apr 2, 2015
    Posts:
    27
    I removed int prefabIndex = -1 and dragged the Tmanager inside the level manager and now it works :eek: but I am getting an IndexOutOfRangeException: Array index is out of range and its point to this line within SpawnTile2
    go = Instantiate(increasedDifficultytilePrefabs[RandomPrefabIndex()]) as GameObject;

    I'm trying to understand why it is out of range hmm

    Edit so i added 0 to Tmanager.SpawnTile2(0); and now i have fixed the problem but I do not understand why it works. o_O:rolleyes:


    Code (CSharp):
    1. public void SpawnTile2(int prefabIndex = -1)
    2.     {
    3.         GameObject go;
    4.         if (prefabIndex == -1)
    5.             go = Instantiate(increasedDifficultytilePrefabs[RandomPrefabIndex()]) as GameObject; //Here is where the
    6. //
    7.         else
    8.             go = Instantiate(increasedDifficultytilePrefabs[prefabIndex]) as GameObject;
    9.         go.transform.SetParent(transform);
    10.         go.transform.position = Vector3.forward * spawnZ;
    11.         spawnZ += tileLength;
    12.         activeTiles.Add(go);
    13.  
    14.  
    15.     }
     
    Last edited: Dec 6, 2017
  5. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I'm glad it's working (mostly) :)

    Well, when it's -1 (or just default/empty), it takes a random spot from a method.. so that part should work.
    If you had code that called that method without any parameter, it would try to index -1 in the list/array, and that is obviously not valid :)
     
    JoeStrout and KUFgoddess like this.