Getting a Missing Reference Exception on a Vector 3

Updated on April 29, 2019 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on April 28, 2019

Hello,

I am trying to make a character selection system and I am getting a Missing Reference Exception on a vector 3 when I switch to a new character. The Vector 3 that is giving me the error is on the camera. The Camera has a script which tries to follow the character. Here is the line that is throwing the error.

Vector3 desieredPosition = target.position + offset;

I have tried putting this line in an if statement that checks to see if the target is != to null but then I am getting an error that says that it cannot be declared within this scope. Here is the entire camera follow script as well. 

 

public class CameraFollow : MonoBehaviour {
public Transform target;
 public float smoothSpeed = 0.125f;
 public Vector3 offset;
public bool bounds;
public Vector3 minCameraPos;
 public Vector3 maxcameraPos;
void FixedUpdate()
 {
 Vector3 desieredPosition = target.position + offset;
 Vector3 smoothedPosition = Vector3.Lerp(transform.position, desieredPosition, smoothSpeed);
 transform.position = smoothedPosition;
if(bounds)
 {
 transform.position = new Vector3(Mathf.Clamp(transform.position.x, minCameraPos.x, maxcameraPos.x), Mathf.Clamp(transform.position.y, minCameraPos.y, maxcameraPos.y), Mathf.Clamp(transform.position.z, minCameraPos.z, maxcameraPos.z));
 }
 }
void Update()
 {
 target = GameObject.FindGameObjectWithTag("Player").transform;
 }
void Start()
 {
 target = GameObject.FindGameObjectWithTag("Player").transform;
 } 
}
  • Liked by
Reply
0 on April 29, 2019

1.) you shouldn’t do FindGameObject in an update loop, or really try to avoid them all together if possible.

2.) try adding this if statement to the beginning of your FixedUpdate

if(target == null) return;

IDK how you were doing it before that said it cannot be declared, but this should stop it from going forward until target is properly assigned.

  • Liked by
Reply
Cancel