Sign in to follow this  
4d69636861656c

Unity Object reference not set to an instance of an object

Recommended Posts

I'm having this problem in Unity when trying to initialize a few variables. I have an example below.

 

public class PlanetDetails
    {
        private int planetID;
        private string planetName;

        public int PlanetID
        {
            get { return planetID; }
            set { planetID = value; }
        }

        public string PlanetName
        {
            get { return planetName; }
            set { planetName = value; }
        }
    }

 

PlanetDetails[] Planet = new PlanetDetails[10];
 

...

 

Planet[i].PlanetID = (System.SystemID + Random.Range(0, 1000));
Planet[i].PlanetName = "Test" + i;
Debug.Log(Planet[i].PlanetID);
Debug.Log(Planet[i].PlanetName);

 

When I try to initialize a variable, it gives me an error in Unity, and since I'm pretty new to programming,  I can't understand why. Any help would be great.

Share this post


Link to post
Share on other sites
Planet[i] = new PlanetDetails();
You can only skip that step if you're using an array of value types (int, bool, float, enum, struct - basically everything that's not a class).

When you make an array, its entries are all set to the "default" value of the corresponding type.

int: 0
float: 0.0f
double: 0.0
all the other numeric and enum types = whatever their concept of 0 is.
bool: false
class: null
struct: non-null, each individual field = its own default

In this case you have a class, so the default is null; You need to individually 'new' each element in the array. Edited by Nypyren

Share this post


Link to post
Share on other sites

What is the exact error message, and what line is it on?

 

NullReferenceException: Object reference not set to an instance of an object
GameGUISystemDetails.Start () (at Assets/Scripts/GameGUISystemDetails.cs:157)

 

The line is this: Planet[i].PlanetID = (System.SystemID + Random.Range(0, 1000));

If I comment this line, the warning will go to the next line, which is the initialization of Planet[i].PlanetName and so on.

Share this post


Link to post
Share on other sites

So the problem is that you are expecting the elements of the array to be there, but they're not.  You're only allocating the space for the elements in your array, you then need to put something there.  

PlanetDetails[] Planet = new PlanetDetails[10];
for(int i=0; i<10;i++)
  Planet[i]=new PlanetDetails();

Cheers, 

 

Bob

Share this post


Link to post
Share on other sites

So the problem is that you are expecting the elements of the array to be there, but they're not.  You're only allocating the space for the elements in your array, you then need to put something there.  

PlanetDetails[] Planet = new PlanetDetails[10];
for(int i=0; i<10;i++)
  Planet[i]=new PlanetDetails();

 

:D Thank you, I completely forgot about that ...

Share this post


Link to post
Share on other sites

The Linq based solution is below, I prefer as less "moving parts" to screw up :)

 

PlanetDetails[] Planet = Enumerable.Repeat(0, 10).Select(_ => new PlanetDetails()).ToArray();

 

I am using _ as the select variable passed in as it is not used

Share this post


Link to post
Share on other sites

As a follow up, in the above Range and Repeat are interchangeable given we are not using the value in _

 

var Planet = Enumerable.Repeat(0, 10).Select(=> new PlanetDetails()).ToArray();

 

 

var Planet = Enumerable.Range(0, 10).Select(=> new PlanetDetails()).ToArray();

 

There is a more subtle use of repeat

 

Func<PlanetDetails> buildPlanet = () => new PlanetDetails();

var Planet = Enumerable.Repeat(buildPlanet, 10).Select(build => build()).ToArray()

 

This returns the same planet factory 10 times, we then call the builder in each case and slot the results into an array

 

:)

Share this post


Link to post
Share on other sites
Just curious: My C# is rusty, but isn't there anything like this?
 
private static IEnumerable<T> Generate(Func<T> f) {
    while (true) yield return f();
}

Used like so:
 
var Planets = Generate(() => new PlanetDetails()).Take(10).ToArray();

Feels a bit more straightforward than WozNZ's suggestions. Edited by kloffy

Share this post


Link to post
Share on other sites

Just curious: My C# is rusty, but isn't there anything like this?
 

private static IEnumerable<T> Generate(Func<T> f) {
    while (true) yield return f();
}
Used like so:
 
var Planets = Generate(() => new PlanetDetails()).Take(10).ToArray();
Feels a bit more straightforward than WozNZ's suggestions.

 

 

Nice one, very explicit. For some reason I forgot about using a generator

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Announcements

  • Forum Statistics

    • Total Topics
      628336
    • Total Posts
      2982157
  • Similar Content

    • By Afambus
      Hello,
      I have a full experienced team that looking for a composer and another 3d designer, im expecting as much from you there are other people in this server that can help you we have a determined team, we have done many things in our game there is more information in the discord about everyone and there skills there region and about the game, if you join the discord pm asap
      https://discord.gg/b2teN3m
    • By BAG Labs
      Mobile SoS

      Platform: Android
      Genre: Board
      Link: Google Play
       
      This games sharpen memory and test your strategies to place S-O-S pattern within time limit and serve 3 difficulties as Easy, Normal, and Hard.

      Goals of the game is to put S-O-S words in patterns (Horizontal, Vertical, and Diagonal) alternately with enemy.
       
      Features:
      Single Player Multiplayer Achievements Leaderboards  
       
      Screenshot:

       

       

       
      Link: Google Play
       
      Please help us improve this game with review
    • By abarnes
      Hello!
      I am a game development student in my second year of a three year program and I would like to start building my portfolio. I was thinking of creating some games to show what I can do to potential employers since I wont have any work related experience when I graduate. But as I'm sure you all know there are tons of ways to approach developing/designing a game and I'm curious if anyone had any insight as to any "standards" that come with this? Is it okay to use game engines like Unity, Unreal, Game Maker etc? Or would it be better to make a game from scratch to better show case your skills? Any and all advice will be greatly appreciated!
    • By Hilster
      Hello 2D Artists,
      I've started making a 2D Puzzle Adventure game for mobile and I'm looking for someone who would want in on creating assets for the game. The core of the programming is pretty much complete, you can walk within the grid laid out and push boxes, when there is an object on top of a pressure pad it will activate the linked objects or if there is one object with multiple linked pressure pads it requires you to activate all points for the object to become active. 

      The level iteration for the game is quick and simple, a Photoshop file that is made of individual pixels that represents objects is put into the game and it creates the level out of those pixels with the assigned objects.
      The objects that need sprites created so far is the character, box, pressure pad, door, trap door, the walls, the stairs and the tiled background.
      I intend to add more objects so the amount I'd like to add will be extended.
      My motivations for posting here is to have something that looks nice to be able to display on my portfolio, so if you're looking for a working game that you can place your art into and improve the look of your portfolio then we're in business.
      Please reply with a few past examples of your art below and I'll be in touch!
    • By thefollower
      Hi
      I have set up my TcpClient to connect to my server and that works fine. But i am a bit confused how i read messages from the network stream with it continuously running via async, without ever closing the connection ?
      My TcpClient Manager class has:
       
      public async Task<bool> Connect(string address, int port) { try { await _tcpClient.ConnectAsync(address, port); IsConnected = true; return true; } catch(Exception e) { Debug.Log(e); return false; } } public async Task<int> Read(byte[] readBuffer) { if (!IsConnected) return -1; using (var networkStream = _tcpClient.GetStream()) { try { var bytesRead = await networkStream.ReadAsync(readBuffer, 0, readBuffer.Length); return bytesRead; } catch (Exception e) { Debug.Log(e); IsConnected = false; return -1; } } }  
      So i thought to just run a co-routine and call Read constantly to get the most recent message, but that doesn't make much sense to me since a co-routine would be blocked with the await. How is this actually done? The MS Docs don't have very good Async examples with the TcpClient class so i don't know fully get how to keep calling Read correctly.
  • Popular Now