- Home /
Ray Cast Click on Enemy - Change Current Target
My raycast target enemy works perfect, my only problem is when I have a target the only way to untarget is to kill the enemy or to right click. I want to make it so if I have a target and i choose to click another one, the target will change. Cant figure it out!
void Update () {
if( Input.GetMouseButtonDown(0) && newon == true)
{
Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
RaycastHit hit;
if( Physics.Raycast( ray, out hit, 100 ) )
{
float distance = Vector3.Distance(hit.transform.position, transform.position);
if(distance < 8) {
string hitTag = hit.transform.tag;
if (hitTag == "enemy" && newon == true)
{
Debug.Log( hit.transform.gameObject.name );
target = hit.transform.gameObject;
SelectTarget();
}
}
}
}
if (Input.GetMouseButtonDown (1)) {
DeselectTarget();
}
Sorry, it's hard to understand if your having trouble changing targets or just de-selecting the chosen target. If you'd like to just get rid of the variable assigned to "target", then why not just do..
target = null;
I don't know what that "newon" does, but it looks like some function falsely modified "newon" variable, causing it doesn't raycast at all.
newon just is a made up variable that checks if a target is selected or not.. and i want to make it so if a target is selected when I click a differnt game object that game object becomes the new target
Answer by EHogger · Jan 05, 2014 at 04:34 AM
If "newon" is to check that a target is already selected, then if you want to be able to select a new target anyway all you have to do is remove the if newon = true
part.
Depending on what those functions do you may also need to add DeselectTarget() on the line before SelectTarget()
Just as an aside, youre checking for newon = true twice in the same if statement. Lines 4 and 17 on here. Since that second one is nested within the first if statement it isn't needed anyway.
Your answer
![](https://koobas.hobune.stream/wayback/20220613125548im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Follow Nearest Target 1 Answer
Raycast target sight? 0 Answers
Enemy does not look the player 2D platformer. 1 Answer
Look at enemy 1 Answer
Hitmarker appears on both targets 2 Answers