- Home /
Raycast Targeting issue
I am trying to setup an Raycast so that when it hits an enemy it brings up that enemys gui bar. Currently I have it showing up the enemy gui bar but it flashes on and off over and over. If I take out the parts of curTarget it stops flashing but if I go over a target then straits over another target it dont change the targeting because it dont turn the last one off,
Here is my code :
using UnityEngine;
using System.Collections;
public class GuiTarget : MonoBehaviour {
private int Range= 70;
public string name = "name";
public bool curTarget = true;
void Update (){
RayShoot();
}
void RayShoot (){
RaycastHit hit;
Vector3 facingDirection= transform.TransformDirection(Vector3.forward);
Debug.DrawRay(transform.position, facingDirection * Range, Color.blue);
if (Physics.Raycast(transform.position, facingDirection,out hit, Range))
{
while(curTarget == true)
name = (hit.collider.gameObject.name);
GameObject varGameObject = GameObject.Find(name);
varGameObject.GetComponent<EnemyHealth>().canShow = true;
curTarget = false;
}
else
{
if(curTarget == false)
{
GameObject varGameObject = GameObject.Find(name);
varGameObject.GetComponent<EnemyHealth>().canShow = false;
curTarget = true;
}
}
}
}
Answer by pako · Dec 23, 2012 at 06:45 PM
Try this:
using UnityEngine;
using System.Collections;
public class GuiTarget : MonoBehaviour {
private int Range= 70;
public string name = "name";
public bool targetWasHit = false; //public only because you had curTarget as public
private GameObject varGameObject;
private bool colliderHit;
void Update (){
RayShoot();
}
void RayShoot (){
RaycastHit hit;
Vector3 facingDirection= transform.TransformDirection(Vector3.forward);
Debug.DrawRay(transform.position, facingDirection * Range, Color.blue);
colliderHit = Physics.Raycast(transform.position, facingDirection,out hit, Range);
if (colliderHit && !targetWasHit)
{
//Set targetWasHit Flag
targetWasHit = true;
name = (hit.collider.gameObject.name);
varGameObject = GameObject.Find(name);
varGameObject.GetComponent<EnemyHealth>().canShow = true;
}
else if(!colliderHit && targetWasHit)
{
{
varGameObject.GetComponent<EnemyHealth>().canShow = false;
targetWasHit = false;
}
}
}
}
Work great thanks. Just a side note you missed the semicolin after "targetWasHit = true" Just incase any one else looks at this for help.
Good to hear that it works. Sorry, I missed the semi colon.
$$anonymous$$aybe then you mark the question as "answered" using the green tick mark.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity c# Raycast axis stuck on one axis 0 Answers
raycast to select transform but not sphere collider 2 Answers