Instantiating within Update, and then moving the object

So I’m raycasting and want to instantiate an object, and then move it around based upon where I look. I just want to instantiate once, and then move that object. This is my code so far (all of this is in a function Update):

//snippet
	if (!bombGhostActive){
		var bombPlacement : GameObject = Instantiate(bombGhost, hit.point, hitDir);
		bombGhostActive = true;
	}
	bombPlacement.transform.position = hit.point;
	bombPlacement.transform.rotation = hitDir;
//end of snippet

But when I do this, the bombGhost is instantiated, but I’m unable to move it and I get a “NullReferenceException: Object reference not set to an instance of an object.” error. Any clues?

bombPlacement only exists within the if statement, and you should always check if something is null.

Thanks much callahan. So hows the best way to be able to access the instantiated object outside that if statement? I’m afraid of using any sort of GameObject.Find as it’s in a Update function, and that seems really expensive.

You’ll want to store it as a private variable attached to the script itself:

private var bombPlacement : GameObject = null;

private function Update()
{
	//not sure on how you handle these
	var hit = GetYourHit()?
	var hitDir = GetYourHitDirection()?
	var bombGhostActive = GetYourBombGhostActive()?
	
	if (!bombGhostActive)
	{
		bombPlacement = Instantiate(bombGhost, hit.point, hitDir);
		bombGhostActive = true;
	}

	if (bombPlacement != null)
	{
		bombPlacement.transform.position = hit.point;
		bombPlacement.transform.rotation = hitDir;
	}
}

EDIT:
If you do a bit of abstraction, it becomes a bit easier to follow and manage/maintain the logic as well:

private var bombPlacement : GameObject = null;

private var hit;
private var hitDir;
private var bombGhostActive : bool;

private function Update()
{
	GatherHitInfo();

	if (!bombGhostActive)
	{
		ActivateBombGhost();
	}
	
	if (HasBombPlacement())
	{
		UpdateBombPlacement();
	}
}

private function GatherHitInfo()
{
	//not sure on how you handle these
	hit = GetYourHit()?
	hitDir = GetYourHitDirection()?
	bombGhostActive = GetYourBombGhostActive()?
}

private function ActivateBombGhost()
{
	bombPlacement = Instantiate(bombGhost, hit.point, hitDir);
	bombGhostActive = true;
}

private function HasBombPlacement() : bool
{
	return bombPlacement != null;
}

private function UpdateBombPlacement()
{
	bombPlacement.transform.position = hit.point;
	bombPlacement.transform.rotation = hitDir;
}

Thanks very much. I (obviously) sometimes struggle with scope issues. Next time either of y’all are in San Antonio, let me know - I owe you a beer!