Smooth Follow 2D works but Null Reference Error Remains

Good morrow people of Unity,

I have a smooth follow script attached to the main camera which finds and follows the instantiated ball. This works fine.

Though between the point of the ball being destroyed and re-spawned the null reference appears. This is because the code is returning NULL to the GameObject.FInd bit. It does not effect the running of the game in unity though when I try to publish in Xcode this error stops it working :frowning:

My question is how do I get around this. I was thinking maybe attach the script to the ball so that it only runs when in the scene??? But i’m not sure.

Also If there is a method that doesn’t involve gameObject.Find that would be awesome as I am publishing for IOS.

Any guidance would be extraordinary!
Thanks legends.

CODE:

      var smoothTime = 0.3;
      private var velocity : Vector2;
      var thisTransform : Transform;
      var target : Transform;
      
      function Update()
       {
	thisTransform = transform;
		
	target = GameObject.Find("ball(Clone)").transform;
	
	if(!target){

	} else if (target) {

	thisTransform.position.x = Mathf.SmoothDamp( thisTransform.position.x, 
		target.position.x, velocity.x, smoothTime);
	
        thisTransform.position.y = Mathf.SmoothDamp( thisTransform.position.y, 
		target.position.y, velocity.y, smoothTime);
		} 
      }

NullReferenceException errors mean that the object you are trying to get does not exist. In this case, the gameobject.find is not finding anything, meaning the variable ball is not set, throwing the null error.

What I would do is set the ball variable through the respawn script, like this:
respawnScript:

function OnRespawn()
{
    //NOTE: this is just an example function name, use your function, obviously
	Camera.main.GetComponent(FollowObjectScript).target = transform;
}

FollowObjectScript:
var smoothTime = 0.3;

private var velocity : Vector2;
private var thisTransform : Transform;

public var target : Transform;


function Update()
{
    if(target) {
		thisTransform.position.x = Mathf.SmoothDamp( thisTransform.position.x, 
		target.position.x, velocity.x, smoothTime);

        thisTransform.position.y = Mathf.SmoothDamp( thisTransform.position.y, 
		target.position.y, velocity.y, smoothTime);
	} 
	thisTransform = transform;
}

This is also much more efficient then running the find command every loop. The find command loops through all game objects in the scene. That means the more objects you have in the scene, the slower it will go, and is a general waste of speed. Sure, it’s nice to use some times, but really should not be run every frame. The way I did it above is much faster as it’s just setting the reference value, and only does it on the respawn event.

Hope this helps.