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

NullPointExeption in simple Script

Discussion in 'Scripting' started by RPGFabi, Jan 5, 2020.

  1. RPGFabi

    RPGFabi

    Joined:
    Oct 24, 2019
    Posts:
    29
    Hey,
    I'm trying to create a small ModManager. My Problem, which occured as soon as I'm trying to Add Mods to a Dictionary, is a NullPointExeption.

    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. ModManager.Awake () (at Assets/Scripts/ModManager.cs:30)
    3.  
    This is my Script
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class ModManager : MonoBehaviour
    6. {
    7.     public static ModManager instance;
    8.     public Dictionary<string, string> LoadedMods;           //Modname (value),  Modpath (key)
    9.     public Dictionary<string, string> LoadedModsVersion;    //Version (value),  Modpath (key)
    10.  
    11.     void Awake()
    12.     {
    13.         if (instance == null)
    14.         {
    15.             // No other Mod Manager excisting
    16.             instance = this;
    17.         }
    18.         else if (instance != this)
    19.         {
    20.             // if this Instance is not the active Mod Manager
    21.             Destroy(gameObject);
    22.         }
    23.         DontDestroyOnLoad(gameObject);
    24.  
    25.  
    26.  
    27.         // ADD Default Mods to test
    28.             for (int i = 0; i < 12; i++)
    29.             {
    30.                 LoadedMods.Add("Modpath_" + i, "Modname_" + i);
    31.                 LoadedModsVersion.Add("Modpath_" + i, "Version_" + i);
    32.                 Debug.Log("Added "+i+ " Mods");
    33.             }
    34.     }
    35. }
    36.  
    This is the Line Which makes Problems:
    LoadedMods.Add("Modpath_" + i, "Modname_" + i);


    Why do I get thoose Errors and how can i fix them?
     
  2. eliyah

    eliyah

    Joined:
    May 4, 2019
    Posts:
    6
    you never initialized LoadedMods Variable
    Code (CSharp):
    1. public Dictionary<string, string> LoadedMods = new Dictionary<string, string>();
     
  3. RPGFabi

    RPGFabi

    Joined:
    Oct 24, 2019
    Posts:
    29
    Thanks, me idiot ...