- Home /
hi,Why the raycast is having object reference error on the : "if (hit.collider.gameObject.tag == "Player") " line? thanks
void Start () {
player = GameObject.Find("Player").transform;
}
// Update is called once per frame
void Update () {
RaycastHit2D hit = Physics2D.Raycast(gameObject.transform.position,player.transform.position, 100f);
Debug.DrawLine (gameObject.transform.position,player.transform.position, Color.cyan);
if (Vector2.Distance (transform.position, transform.forward) < shootdist)
{
transform.LookAt (player.position);
transform.Rotate (new Vector3 (0, -90, 0), Space.Self);
if (hit.collider.gameObject.tag == "Player")
{
nextshoot -= Time.deltaTime;
}
}
if (nextshoot < 0)
{
nextshoot = timebetweenshots;
Rigidbody clone;
clone = Instantiate (projectile, transform.position, transform.rotation) as Rigidbody;
}
}
Answer by Bunny83 · Apr 19, 2018 at 12:27 PM
The 2d raycast works different from the 3d raycast. While the 3d raycast returns true or false whether there's a hit or not, the 2d version always returns a "RaycastHit2D" struct, even when there's no hit at all. That's why, if you care to check the example in the docs, you have to check if the hit struct actually contains a valid collider reference or not. That means if there's no hit at all the collider reference in your "hit" will be null.
yes i needed condition --> if hit.collider != null...thanks again b
Answer by Vollmondum · Apr 19, 2018 at 11:35 AM
Assign Player as public variable instead of finding it, or add if(player != null), otherwise you're checking null object, if Find line failed
i got it serialised,its a find, but, for some reason if i stand on the right side of turret, it shoots properly
Sounds like my ex-issue, the 2d game should be in one axis coordinate segment. say all X and Y should be > 0. $$anonymous$$ove everything away from 0 coordinate into one quarter
yes that changed behaviour too, although ,it wasn't the issue now, i sure 'll keep that in $$anonymous$$d thanks for the heads up :)
Your answer
