- Home /
Help me in Targeting with Raycast please.
I want to make a script what selects a transform as target what is hitted by the ray. I want to turn the Target to red, and when the Ray isn't colliding with it, then it turns back to the original color. I made this script, but it is not what I want.
using UnityEngine; using System.Collections;
public class Targeting : MonoBehaviour {
public Transform target;
public int range = 20;
void Update ()
{
Debug.DrawRay(transform.position ,transform.forward*range,Color.red);
Vector3 forward = transform.TransformDirection(Vector3.forward);
RaycastHit hit;
if (Physics.Raycast(transform.position, forward, out hit))
{
target = hit.transform;
target.renderer.material.color = Color.red;
}
else target.renderer.material.color = Color.grey;
}
} How can i turn the previous target's color back to the original when i chose another target?
This is a duplicate question of: http://answers.unity3d.com/questions/249016/how-can-i-chose-the-previous-target.html
Answer by aldonaletto · May 06, 2012 at 05:44 PM
This may become complicated because the ray may hit many different objects, and you can't keep track of which object had which color. You can try the following: save the current object reference and color; next Update, if the hit object changed, set the old object color before updating the current object/color - like this:
using UnityEngine; using System.Collections;
public class Targeting : MonoBehaviour {
public Transform target;
public Color targetColor; // save the original color
public int range = 20;
void Update (){
RaycastHit hit;
// use transform.forward directly instead of calculating the forward direction:
if (Physics.Raycast(transform.position, transform.forward, out hit)){
// if something hit, check if it's a new object:
if (hit.transform != target){ // if so,
RestoreColor(); // restore the previous object color...
target = hit.transform; // update the target object...
targetColor = target.renderer.material.color; // and save its color
target.renderer.material.color = Color.red; // then paint it red
}
}
else { // if nothing hit, restore the last object (if any) original color:
RestoreColor();
}
}
void RestoreColor(){
if (target){ // if there exists a previous target, restore its original color:
target.renderer.material.color = targetColor;
}
}
}