So, what i want to reach is that wen the RayCast hit a object with the tag “BuildPath”
it wil set that gameobject as Selected object so i can use that object later on again.
but, wen i hit another object with the same tag i want SelectedPath to be LastSelected.
I don’t know what i did wrong!
Thnx for al help already!!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Raycast : MonoBehaviour {
public float InteractDistance = 5;
[Space(10)]
public GameObject SelectedPath;
public GameObject LastSelected;
void Update()
{
//-----------------------------------------------------------------------------
Vector3 forward = transform.TransformDirection(Vector3.forward) * InteractDistance;
Debug.DrawRay(transform.position, forward, Color.red);
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, InteractDistance))
{
//---------------------------------------------------------------------------------------------------------
//Wallbuild
if (hit.collider.gameObject.tag == "BuildPath")
{
SelectedPath = hit.collider.gameObject;
if(hit.collider.gameObject.GetInstanceID() == SelectedPath.GetInstanceID())
{
LastSelected = SelectedPath;
}
}
}
}
}
Sorry if I misunderstood, but it sounds like you want to do this:
if (hit.collider.gameObject.tag == "BuildPath")
{
// Set the current selected path to be the last selected path
LastSelected = SelectedPath;
// Set the hit buildpath to be the selected path
SelectedPath = hit.collider.gameObject;
}
The problem is that both SelectedPath and LastSelected are becoming the same object then.
And what i try to do is wen you hit with the raycast “Plane1” it shows plane1 as SelectedPath but if you go to plane2 and hit that one it wil set plane1 to lasSlected and plane2 as SelectedPath.
Timelog’s suggestion should work unless the code is constantly firing. If it fires in the update, that would set both to the same object after the second pass of that script. How are you limiting the code from constantly firing? Maybe the distance isn’t enough of a condition to keep the code from firing twice or more when it should only fire once.
I completely looked over the fact the raycast is done on update. You’d normally see that in some kind of input action. But if you need to do it on each Update, then this check should make sure it only updates the references when you don’t hit the same object:
if (hit.collider.gameObject.tag == "BuildPath")
{
// Only update if the current hit object is not the current selected object
if(hit.collider.gameObject.GetInstanceID() != SelectedPath.GetInstanceID())
{
LastSelected = SelectedPath;
SelectedPath = hit.collider.gameObject;
}
}