Cannot find Instanciated object

Hello,

I am just starting with programming in c#, but i seems I hit the wall. The point of this script is to spawn an object called “Log 0” and then find this new object and set one of its bools to true. But whatever I do I cannot find this object and get error
“NullReferenceException: Object reference not set to an instante of an object.”

I feel that my mistake is really basic, somewhere:)

        if (nextToChest == true && player.GetComponent<PlayerMovement> ().isCarrying == false && Input.GetKeyDown(KeyCode.E) && logCountNumber > 0) //if player is near and there are logs in the chest
        {
            playermovement.isCarrying = true; 
            Instantiate (log, cuttingTrigger.position, cuttingTrigger.rotation);
            GameObject.Find ("Log " + logOrder).GetComponent<LogScript> ().followPlayer = true; //find log and set it to follow the player
            logCountNumber--; //one less log in the chest
        }

I think there is even simplier solution to my problem, but I cannot solve this one and its driving me crazy. Thanks for any help.

Hi and welcome to the forums!

You’ll want to store the instantiated object in a variable, then work on that.
Something like this:

var newLog = Instantiate (log, cuttingTrigger.position, cuttingTrigger.rotation);
newLog.GetComponent<LogScript>().followPlayer = true; //find log and set it to follow the player
// do other stuff with the new log

See here for the section in Learn that shows an example. You might want to go through the other topics there as well, as they’re pretty nicely bite-sized to be easily digestible.

2 Likes

That is it! I knew its gonna be something like that! Thanks!

Does that actually work without the cast/generic? I would expect to see a “GetComponent is not a member of UnityEngine.Object”.

It’s a simple fix, Simply cast the result of the Instantiate to the appropriate type.

On the other hand if it does work then that’s a new trick for me to add to my bag.

Yes that will not compile unless using the single-parameter overload of Instantiate, and also passing in a MonoBehaviour or GameObject.

1 Like

Oh… you’re right.
I forgot I added an extension method, as I was getting tired of casting to GO everytime when I wanted to instantiate → grab single component.

public static T GetComponent<T>(this UnityEngine.Object obj)
    {
        return ((GameObject)obj).GetComponent<T>();
    }

That way I can do lines like this:

var mover = Instantiate(PrefabToSpawn, spawnLocation, Quaternion.identity).GetComponent<MoveCube>();

So yeah - it needs a cast. Sorry for the confusion :confused:

Original answer should’ve been:

var newLog = (GameObject)Instantiate (log, cuttingTrigger.position, cuttingTrigger.rotation);
newLog.GetComponent<LogScript>().followPlayer = true; //find log and set it to follow the player
// do other stuff with the new log
1 Like