- Home /
Troubles with raycasting to find tags
Hi all,
I've been trying to make a crosshair that changes color when it hovers over objects with particular tags (i.e, "Friend" and "Enemy" tags). I had a look around, and saw you needed to raycast to find such things. Raycasting's unfamiliar territory for me, so I'm kinda flying blind here. This is the script I have:
var crosshairTexture : Texture2D; var crosshairRange = 200;
private var hit : RaycastHit; private var facingDirection = transform.TransformDirection(Vector3(0,0,1));
function Update () { if (Physics.Raycast(transform.position, facingDirection, hit, crosshairRange)) { if(hit.collider.gameObject.tag != "Untagged") { if (hit.collider.gameObject.tag = "Enemy") { crosshairTexture.color = Color.(1, 0, 0, 0.5); }
else if (hit.collider.gameObject.tag = "Friend")
{
crosshairTexture.color = Color.(0, 1, 0, 0.5);
}
else
{
crosshairTexture.color = Color.(1, 1, 1, 0.5);
}
}
}
}
In line 13 - if (hit.collider.gameObject.tag = "Enemy")
it comes up with the error "expecting ), found =." and also "Unexpected token Enemy." I've tried a few different versions of the hit.collider.gameObject.tag thing, none of which have worked. I know this is probably just a simple mistake (last time I forgot to capitalize a 'u') but I can't for the life of me figure it out.
Any help would be appreciated!
You're right, it is a simple (and common) typo. It should be hit.collider.gameObject.tag == "Friend" ins$$anonymous$$d of hit.collider.gameObject.tag = "Friend" (note double-equals)
Sadly I tried that, and now there's 27 errors ins$$anonymous$$d of just 2. Tried a couple variations again, but still the same. Any other suggestions?
Answer by Kristov · Oct 26, 2010 at 05:28 AM
Was answered on another forum, to anyone who's got the same problem. Basically the solution was to change the gameObject.tag == "Enemy"
and so on to gameObject.CompareTag("Enemy")
If you wanna see the whole script, the link is http://forum.unity3d.com/threads/64880-Troubles-with-raycasting-to-find-tags.