- Home /
Question by
LPGaming · Jan 17, 2013 at 10:05 AM ·
physicsraycastingtargetting
Need help with basic target system
So, i have my targetting system working correctly. I'm trying to change the color of the object to red when it's targetted, which also works.. The problem is when I click on the NPCs they turn red, but they turn red one by one, when the target is no longer the target, it's still red. I understand that's what my code does, but I'm curious as how to make it only show red if it is the current target.
using UnityEngine;
using System.Collections;
public class RaycastTargetting : MonoBehaviour {
RaycastHit hit;
Ray ray;
public Transform target;
void Update (){
if (Input.GetButton("Fire1")){
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (ray, out hit, 250)){
if (hit.transform.tag == "NPC"){
target = hit.transform;
ApplyTarget(target);
}
}
}
}
void ApplyTarget(Transform theTarget) {
theTarget.renderer.material.color = Color.red;
}
}
Comment
Answer by Imankit · Jan 17, 2013 at 10:56 AM
using UnityEngine;
using System.Collections;
public class RaycastTargetting : MonoBehaviour {
RaycastHit hit;
Ray ray;
public Transform target;
void Update (){
if (Input.GetButton("Fire1")){
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (ray, out hit, 250)){
if (hit.transform.tag == "NPC"){
target = hit.transform;
ApplyTarget(target);
}else{
target.renderer.material.color = Color.black; // Any color you had previous..
}
}
}
}
void ApplyTarget(Transform theTarget) {
theTarget.renderer.material.color = Color.red;
}
}