Turning off a script when Raycast leaves object
Hi Folks,
So i'm having some difficulty with Raycasts and turning on and off scripts depending on whether the ray hits within a certain distance.
Currently my script highlights the object by changing the material color when within a certain distance (pick-up distance), but I also want it to turn on a script on the object, and then turn it off when the Raycast is no longer colliding.
Any help would be great, as it can currently turn the script on, but crashes when leaving the object (where it should turn off).
Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HighlightObjects : MonoBehaviour {
public float highlightrange;
public string ObjectIdent;
private Color highlight;
Material originalmat, tempmat;
Renderer render = null;
PickUpCode pickupcode;
// Use this for initialization
void Start () {
highlight = Color.black;
}
// Update is called once per frame
void Update () {
RaycastHit hitInfo;
Renderer currentrender;
Debug.DrawRay(this.transform.position, this.transform.forward * highlightrange, Color.blue);
if(Physics.Raycast(this.transform.position, this.transform.forward, out hitInfo, highlightrange)){
currentrender = hitInfo.collider.gameObject.GetComponent<Renderer>();
pickupcode = hitInfo.collider.gameObject.GetComponent<PickUpCode>();
if (currentrender == render)
return;
if (currentrender && currentrender != render){
if (render){
render.sharedMaterial = originalmat;
}
}
if(currentrender)
render = currentrender;
else
return;
originalmat = render.sharedMaterial;
tempmat = new Material(originalmat);
render.material = tempmat;
render.material.color = highlight;
pickupcode.enabled = true;
}
else{
if(render){
render.sharedMaterial = originalmat;
render=null;
pickupcode = hitInfo.collider.gameObject.GetComponent<PickUpCode>();
pickupcode.enabled = false;
}
}
}
}
Answer by Bairne · Feb 07, 2018 at 12:01 AM
Managed to answer my own question! Essentially had to save the last hit object as a public variable, then use that to turn off the script when the raycast left it.
Your answer
![](https://koobas.hobune.stream/wayback/20220612152112im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
RayCast2D and RayDraw errors 0 Answers
How would I project a Gameobject onto the surface of another? 0 Answers
raycasting doesn't work 1 Answer