-1
\$\begingroup\$

I want my gameObject 'spawned' to divert in the direction of vector divert when it collides with the GameObject with which this script is attached, but it keeps showing null reference exception every time when the collision occurs but diversion isn't happening! I don't know why this is happening..

Can anyone tell me how to do this.

public class BallCollision : MonoBehaviour {
  public Transform central;
  public Transform centre;
  BallMovement ballMovement = null;
  Vector3 horizontal ;
  Vector3 vertical;
  Vector3 divert;
  // Use this for initialization
  void Start () {
  }

  // Update is called once per frame
  void Update () {
    horizontal = this.transform.position - central.position;
    vertical = centre.position - central.position;
    divert = horizontal + vertical;

    Debug.DrawLine (central.position, this.transform.position, Color.red);
    Debug.DrawLine (central.position, centre.position, Color.blue);
    Debug.DrawRay (central.position, divert, Color.green);
  }
  void OnCollisionEnter2D(Collision2D collision)
  {
    Debug.Log ("Collided!");
    ballMovement.spawned.AddForce (divert*5000);
  }
}
\$\endgroup\$
3
\$\begingroup\$

You are missing initialization of ballMovement variable. Collision occurs, game tries to access ballMovement, which is null - Null Reference Exception as result.

\$\endgroup\$
3
\$\begingroup\$

You are more than likely not setting your BallMovement variable:

BallMovement ballMovement = null;

Seeing as it is marked as private, and seeing that you are not setting this in code and then attempting to use it.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.