- Home /
Answered my own question.
How to make a gun autoaim on targets under the reticule?
Hey all. I'm new to Unity, and C# too, so apologies if the answer is obvious.
Basically, I'm trying to make a gun that automatically targets and auto-aims at any GameObject tagged "Enemy" which passes under the player's aiming reticule (a GUIElement). Sort of like Star Wars: Battlefront II.
Here's my code so far:
if (!target)
{
if (gunCrosshairs.HitTest(Camera.main.ViewportToScreenPoint(playerTarget.transform.position)))
{ target = playerTarget; }
else
{
GameObject inCrosshairs = transform.gameObject;
}
else if (gunCrosshairs.HitTest(Camera.main.ViewportToScreenPoint((GameObject.FindGameObjectWithTag("Enemy")).transform.position)))
{
GameObject inCrosshairs = transform.gameObject;
if (inCrosshairs.tag == "Enemy")
{
target = inCrosshairs;
}
};
}
if (!gunCrosshairs.HitTest(target.transform.position))
{ target = null; }
Here's how it's supposed to work. If the variable "target" is null (i.e. there was no enemy under the autoaim cursor), the script checks for "Enemy" GameObjects under the targeting reticle. First, it checks for the player's manually selected target GameObject, "playerTarget". If "playerTarget" is not under the reticle (a simple boolean check using HitTest), the script then searches for the first "Enemy" that falls under the crosshair instead.
Once identified, the "Enemy" GameObject under the reticle will be stored in variable "target", which the autoaim will use to aim at that particular enemy. If no "Enemy"'s of any kind are under the autoaim reticle, it will clear the variable "target".
I've been trying to use HitTest to identify when an enemy is under the crosshair. Problem is, since HitTest returns a bool, and I need to store the "Enemy" GameObject to a variable, I don't know how to use HitTest to supply a variable. If that makes any sense.
Also, I'm having trouble with linking my crosshairs GUIElement to this script in the Inspector. Whenever I try to find that GUIElement and drag it to the Inspector, the Inspector doesn't recognize it, even though I added the following public variable to the main script:
public GUITexture gunCrosshairs;
Any idea why the Inspector might not be recognizing the GUIElement I'd already added to the canvas? What settings should I check?
Any help on both (or either) of these questions would be very helpful! :)