Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Nullreferenceexception when change camera

Discussion in 'Scripting' started by Roulik, Mar 13, 2020.

  1. Roulik

    Roulik

    Joined:
    Jan 15, 2018
    Posts:
    14
    I have two cameras in scene, main camera and camera2
    In script i change cameras enabled one and disable the other cam, and in update() i have this:
    Code (CSharp):
    1. Vector2 ray=Camera.main.ScreenToWorldPoint(Input.mousePosition);
    2. gOCollision=Physics2D.Raycast(ray, Vector2.zero);
    3. if(gOCollision.collider.gameObject.name=="PlayerHand" && mainScreen)
    When main camera is disable and camera2 is enable i get nullreferenceexcepcion in line where if() condition, when main camera is enabled and camera2 disable i dont get the nullreference error,
    someone could said me why?
    Thanks
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Physics2D.Raycast is designed to return null when the raycast doesn't hit anything. So you should be checking g0Collision for null first before assuming it is not null like you are currently doing.

    https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html

    As to why your raycast doesn't hit anything when using a different camera, you'll have to investigate since you haven't provided any information as to why that would be the case here.
     
  3. Roulik

    Roulik

    Joined:
    Jan 15, 2018
    Posts:
    14
    I just found why in scene i have a map with boxcollider2d and countries in map have one polygoncollider2d per country, when play scene countries collider are disable and map collider is enable, when click on map his collider is disable and countries colliders are enable, in that moment if click in map but outside of countries gives me error, if i keep map collider enable the error disappear but then i can't click on countries