- Home /
Store previous gameObject that raycast had hit. (Or store any previous value in Update for that matter)
I need a way to store previous gameobject raycast had hit. I do raycast constantly in Update.I want that when i move mouse to new game Object and Current_GameObject_Under_Pointer becomes that new gameObject and Previous_Gameobject becomes gameObject pointer just left, so when i move mouse from object to object i constantly have current and previous objects values.
It’s very easy to do if you do it on mouse click or some other event like that but i can’t figure out how to do it in Update. I tried different ways with states check and with Current_GameObject_Under_Pointer != Previous_Gameobject e.t c
Thank you.
GameObject Current_GameObject_UnderPointer;
GameObject Previous_Gameobject;
void Update () {
Ray Ray= Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(Ray, out hitInfo, 100, GridLayerMask))
{
Mouse_Position = hitInfo.point;
Mouse_Position_Rounded = new
Vector3((Mathf.Round(GW_Mouse_Position.x)), 0,
(Mathf.Round(GW_Mouse_Position.z)));
Current_GameObject_Under_Pointer =
hitInfo.transform.gameObject;
}
}
Answer by FlaSh-G · Jun 20, 2017 at 08:35 AM
var nextGameObject = hitInfo.gameObject;
if(nextGameObject != currentGameObject)
{
previousGameObject = currentGameObject;
currentGameObject = nextGameObject;
}
Well, that's was quick. Thank you. I was statring to get that i need 3rd varible to do that but was't smart enought to figure how to use it.
Well, technically, you don't need it. It's just there for readabilty. You could replace all occurrences of nextGameObject
with hitInfo.gameObject
.