How to instantiate an object?

So I’m procedurally generating myself a map to base the rest of my project off. I’ve developed the terrain generation and that works as I want it to. The next step is to fill it with trees and then put some buildings in, so I’m focussing on the trees first and then afterwards I’ll work on the buildings. I’m planning on using this general process:

  • Create a Perlin noise map
  • Cycle through each point x & y
  • For each point, if the value is above what I specify then add in a tree
  • Instantiate my Tree object

And here is the code currently:

public void PlantTrees()
    {
        float[,] treeMap = Noise.GenerateNoiseMap(mapWidth, mapHeight, treeSeed, treeNoiseScale, octaves, persistance, lacunarity, treeOffset);

        for (int x = 0; x < mapWidth; x++)
        {
            for (int y = 0; y < mapWidth; y++)
            {
                if (treeMap[x, y] >= treeLimValue)
                {
                    float X = x - (mapWidth / 2);
                    float Y = y - (mapHeight / 2);
                    float Z = noiseMap[x, y] * featureMap[x, y] * meshHeightMultiplier;
                    Vector3 treePosition = new Vector3(x, noiseMap[x,y]*featureMap[x,y]* meshHeightMultiplier, y);

                    GameObject newTree = Instantiate(treeObj);
                    newTree.transform.position = treePosition;
                }
            }
        }
    }

The external variables noiseMap, featureMap and meshHeight basically just tell the function how high the current point is and therefore where to place the tree.
The GameObject newTree is just a basic cube asset in my project library for now.

When I try to run this code - using a GUI button in Unity Editor, but I have also tried putting it in a Start() function, which didn’t seem to work either - I get the following error message:
image
I’ve looked online and found someone saying that Instantiation has to happen in the main thread, rather than the GUI button setup I have here, but that seems pointless to me?
I’ve also seen something about making Prefabs of a GameObject and Instantiating those, which I haven’t done here.

Thanks in advance for any help.

sadly for me that error message is teeeny tiny, but what line is that, and what exactly is null? treeobj?? if so, why is it null, you have to have a valid object

This error is not about instantiation, it tells you that you are trying to use a variable that is null (doesn’t point to a object, an object has not been assigned to it) and that variable exists in the AssetMapGenerator.cs script line 312. As we don’t have this, we can’t tell you more about it, but look at that line and try to find what is null there.

Also you mention that you have a GUI button setup in the editor, are you trying to instantiate something in the editor and not at runtime? This has nothing to do with multi threading, it still happens in the main thread. If so, instantiate still works but try looking at https://docs.unity3d.com/ScriptReference/PrefabUtility.InstantiatePrefab.html, that creates a connection to the original prefab.

The answer is always the same… ALWAYS!

How to fix a NullReferenceException error

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that

NullReference is the single most common error while programming. Fixing it is always the same.

Some notes on how to fix a NullReferenceException error in Unity3D:

http://plbm.com/?p=221

1 Like

About the null error stuff,
The cube successfully instantiates once, which makes me think there is something happening between the first and second iteration that wipes the GameObject from memory.
Also here’s the link to guy I found talking about main threads on second reading it looks like he might have a slightly different problem to me:

You do realize that no one can answer your question without seeing the code, right? We have no way of knowing what the issue is, if it is related to instantiation, what is null, or what is happening because you haven’t provided the relevant code.

Remember to attach the Debug of Visual Studio to Unity PlayMode(u can enable it from the little bug at the bottom right of the screen) and use some breakpoints to get what is null and why, almost every null reference exception is fixed like this

That is a PERFECT place to begin your next investigations. Here’s a sample of the thought process:

Step by step, break it down, find the problem.

The NullRef “problem” doesn’t actually change. It’s ALWAYS the same, no matter where it happens, in your code, in Unity’s code, in someone else’s code.

Therefore the answer really is ALWAYS the same. I’m not kidding. There’s never a NullRef that is fixed by any other way.

Ok so for the code lines they’re below:


The line throwing an error is 312, setting the Z, I had a poke at this in Unity and it turns out that this is because my map generation script was tied to a UI button, the featureMap[,] and noiseMap[,] used in the script aren’t created in memory. When I clear this up (i.e. either set the Z to a flat 0 or just click the Generate button in the UI) the error message goes away.
I must have been confused by a previous error message I had - or thought I had - on line 313.
And it works! Second time in this project now I’ve been stumped by an error message and it’s been completely different to what I thought it was. I may have to change around some of the XYZ coordinates because the trees seem to be flipped compared to the map but I’m happy so far.

1 Like

This is a thing for sure. Happens to me ALL the time.

This is why programmers are like we are: we crash it, then crash it again and again and again just to be sure it really is a crash and where it happened.

As the joke goes:

A physicist, engineer, and programmer are in a car…

… when the brakes start to overheat and catch fire.

They pull over and put the fire out, and the physicist says “We should model how the pads interact with the discs at different speeds to see why they’re overheating”.

The engineer says “I’ve got some tools in the back, I’ll adjust the brakes to see if I can stop them overheating”.

The programmer says “Let’s get going again and see if the problem is reproducible”

1 Like

There are only two things in line 312 that could throw a null reference exception. It’s either your noiseMap or your featureMap. That’s it. Those are the only two things which are reference types in that line. So check which is null. This can be done by splitting the line into separate lines or by using some Debug.Log checks before that line. Once you know what is null, you can start searching for the reason “why” it’s null.

Maybe you have some funny business on which object you run this method on. Maybe you created that monobehaviour with new, so it doesn’t have the data. Maybe you called the method on a prefab instead of an actual object in the scene. There are countless potential reasons

Adding Debug.Log statements with context objects can help narrowing down the possibilities

Try using
Debug.Log("PlantTrees", gameObject);
at the start of your PlantTrees method. When you click on the log message, Unity will highlight the gameobject this script is attached to. This can help figuring out “where” your code is actually executing.