Search Unity

Constructor not creating object

Discussion in 'Scripting' started by patgiok, Aug 30, 2019.

  1. patgiok

    patgiok

    Joined:
    Aug 17, 2019
    Posts:
    3
    So i'm trying to create a building prototype and adding that to a list. However after i create the building and try to add it to the list I get a null reference error on line 7 of createAllBuildings
    Might be important, so the createAllBuildings function is in my worldcontroller class and the constructor is in a non monobehavior building data class.
    Debug.Log(b) = Building
    But I cannot access any of b's variables.
    Debug.Log in constructor = this.buildingName: Empty movecost: 1 width: 1 height: 1
    NullReferenceException: Object reference not set to an instance of an object
    WorldController.createAllBuildings () (at Assets/WorldController.cs:185)

    thanks!

    Code (CSharp):
    1.  
    2.     //Create all buildings
    3.     public void createAllBuildings()
    4.     {
    5.         Building b = new Building("Empty", 1f, 1, 1);
    6.         Debug.Log(b);
    7.         Building.BuildingPrototypes.Add("Empty", b);
    8.     }
    Code (CSharp):
    1.  
    2.     public Building(string objectType, float movecost, int width, int height)
    3.     {
    4.         this.buildingName = objectType;
    5.         this.moveCost = movecost;
    6.         this.width = width;
    7.         this.height = height;
    8.         Debug.Log("this.buildingName: " + objectType + buildingName + " movecost: " + movecost + " width: " + width + " height: " + height);
    9.     }
     
    Last edited: Aug 30, 2019
  2. KarlmarBlazehorn

    KarlmarBlazehorn

    Joined:
    Aug 30, 2019
    Posts:
    4
    Its hard to understand whats going on, is the following a static function:
    Code (CSharp):
    1.       Building.BuildingPrototypes.Add("Empty", b);
    Because if it isnt your calling a function that doesnt exist. a full code of building would be useful to see...