Search Unity

Raycast NullReferenceException

Discussion in 'Scripting' started by TreasureChestMimic, Feb 20, 2018.

  1. TreasureChestMimic

    TreasureChestMimic

    Joined:
    Jan 26, 2018
    Posts:
    8
    So I've got a raycast that turns an enemy to ice:

    Code (CSharp):
    1. void Start(){
    2.         iceLayer = LayerMask.NameToLayer ("Ice");
    3.     }
    4.  
    5.     private RaycastHit2D CheckRaycast(Vector2 direction){
    6.         float directonOriginOfsfset = originOffset * (direction.x > 0 ? 1 : -1);
    7.         Vector2 startingPosition = new Vector2 (transform.position.x + directonOriginOfsfset, transform.position.y);
    8.         Debug.DrawRay(startingPosition, direction, Color.red);
    9.         return Physics2D.Raycast(startingPosition, direction, raycastMaxDistance, 1<< iceLayer);
    10.         }
    11.     private bool RaycastCheckUpdate(){
    12.         if(iceGazeCombo.Check() && !GetComponent<playerDoubleJump>().Jumping && !GetComponent<playerSlide>().Sliding){
    13.             Vector2 direction = new Vector2 (1, 0);
    14.             if (GetComponent<playerMovement>().FacingRight == false){
    15.                 direction *= -1;
    16.             }
    17.  
    18.             RaycastHit2D hit = CheckRaycast(direction);
    19.             if (hit.collider.tag == "Enemy")
    20.             if (hit.collider.gameObject.GetComponent<turnIce> ())
    21.                 hit.collider.gameObject.GetComponent<turnIce> ().elapsed = 0;
    22.             if (!hit.collider.gameObject.GetComponent<turnIce> ().ice)
    23.                 hit.collider.gameObject.GetComponent<turnIce> ().turnToIce();
    24.             return true;
    25.         }
    26.         else{
    27.             return false;
    28.         }
    29.     }
    30.     private void FixedUpdate(){
    31.         RaycastCheckUpdate ();
    32.     }
    Works great when I aim at the enemy that can be turned to ice.. Problem is when I don't hit an enemy it gives a NullReferenceException.. Any ideas on why this keep throwing out errors?
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    Just test the returned hit for null before doing any other tests on it.
     
    TreasureChestMimic likes this.
  3. TreasureChestMimic

    TreasureChestMimic

    Joined:
    Jan 26, 2018
    Posts:
    8
    Thank you for the reply. I was coming back to update this post because I did just that and everything is working.
    Thank you again!