So i’m getting this error every time I click on a blue ball with the tag “blueBall” and I cant seem to find how to fix it, the code works and only sets the object the ray hit with that tag as detective but the exception keeps popping up.
using UnityEngine;
using System.Collections;
public class BallScript : MonoBehaviour {
Ray ray;
RaycastHit2D rayHit;
void Update () {
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
rayHit = Physics2D.Raycast(ray.origin, ray.direction);
if(Input.GetKeyDown(KeyCode.Mouse0)){
if(rayHit.collider.tag == "blueBall"){
rayHit.collider.gameObject.SetActive(false);
GameManager.gameManager.SetPlayerScore(GameManager.gameManager.GetPlayerScore()+1);
}else{
Debug.Log("Nada");
}
}
}
}
rayHit will always return true, so add a conditional check like if (rayHit.collider != null) … because if the ray misses you’ll have bogus null data otherwise and it will crash.
You’re blindly expecting to check data that doesn’t exist:
Ya at the start of the game all balls used are instatiated and put into an array and deactivated, then I have a script that sets random balls a position and sets them as active.
I have to use rayHit.collider because rayHit doesn’t have a definition for gameObject.
ya I know I stuck that back in, I took it out before posting thinking that may have been the error.
[UPDATE]
I read over what you wrote and what I picked up from what you said instead of checking if rayHit.collider exists in the same if statement as checking for the tag I mad another if statement before the check for the tag and it worked so thanks man