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.
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.
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
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