- Home /
Problem changing renderer back to original after changing it on raycast hit
Hi all, I have a script that highlights the object in the center of the screen by changing its renderer on hit and storing that object as the original target. It checks to see on hit if the object has a script or not and changes the renderer if it does.
the script swaps it back to its original one once the original target becomes null.
This works fine. the problem is when you have multiple objects and no gap between them in the view point, so effectively the raycast moves between objects and never becomes null, thus multiple objects all highlight.
I have tried to get around this, but to be honest I cannot figure it out. Please can someone help me swap back to the original shader, even if the raycast hit never becomes null?
Here is the code snippet I need to adjust:
public class Player_Script_PickupAndMoveObject : MonoBehaviour {
GameObject mainCamera;
GameObject carriedObject;
int screenX;
int screenY;
bool isCarrying;
public float objectCarryDistance;
public float cameraSmooth;
GameObject targetObject;
GameObject previousObject;
// Use this for initialization
void Start ()
{
mainCamera = GameObject.FindWithTag("MainCamera");
screenX = Screen.width / 2;
screenY = Screen.height / 2;
}
// Update is called once per frame
void Update ()
{
Ray targetRay = mainCamera.camera.ScreenPointToRay(new Vector3(screenX, screenY));
RaycastHit hit;
if (Physics.Raycast(targetRay, out hit))
{
Object_Script_Pickup p = hit.collider.GetComponent<Object_Script_Pickup>();
if (p != null)
{
targetObject = p.gameObject;
p.isTargetted = true;
}
else
{
Object_Script_Pickup targetScript = targetObject.GetComponent<Object_Script_Pickup>();
targetScript.isTargetted = false;
}
}
Many thanks in advance for any help on this!
Answer by Deadcow_ · Apr 05, 2015 at 07:14 PM
// Initialized here to not cause null exception at first update call
Object_Script_Pickup[] cachedSelected = new Object_Script_Pickup[0];
void Update()
{
Ray targetRay = mainCamera.camera.ScreenPointToRay(new Vector3(screenX, screenY));
// All selected at this frame
var currentHits = Physics.RaycastAll(targetRay)
.Select(h => h.collider.GetComponent<Object_Script_Pickup>())
.Where(o => o != null).ToArray();
// There is newly selected objects (current selected except previously cached objects)
var newHits = currentHits.Except(cachedSelected).ToArray();
Array.ForEach(newHits, h => h.isTargetted = true);
// This objects is not selected any more
var wasSelected = cachedSelected.Except(currentHits).ToArray();
Array.ForEach(wasSelected, h => h.isTargetted = false);
cachedSelected = currentHits;
}
Okay, I not tested this piece, but if there is a bug somewhere it wont be to hard to find out how to fix it ;)
Your answer