In this script when there is a detection I'm setting the flag detect to true and using in with other scripts. And using the clickForDescription
flag and OnGui to display text description for each interactable item if there is a text for it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DetectInteractable : MonoBehaviour
{
public Camera cam;
public float distanceToSee;
public string objectHit;
public bool interactableObject = false;
public Transform parentToSearch;
public static bool detected = false;
private RaycastHit whatObjectHit;
private bool clickForDescription = false;
private bool clickForAction = false;
private int layerMask = 1 << 8;
private void Start()
{
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
clickForDescription = true;
clickForAction = true;
}
Debug.DrawRay(cam.transform.position, cam.transform.forward * distanceToSee, Color.magenta);
if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee, layerMask))
{
detected = true;
objectHit = whatObjectHit.collider.gameObject.name;
interactableObject = true;
print("Hit ! " + whatObjectHit.collider.gameObject.name);
}
else
{
detected = false;
clickForDescription = false;
print("Not Hit !");
}
}
private void OnGUI()
{
if (clickForDescription == true)
{
ProcessOnGUI(parentToSearch);
}
}
void ProcessOnGUI(Transform parent, int level = 0)
{
foreach (Transform child in parent)
{
if (child.GetComponent<ItemInformation>() != null)
{
ItemInformation iteminformation = child.GetComponent<ItemInformation>();
if (child.name == objectHit)
{
var centeredStyle = GUI.skin.GetStyle("Label");
centeredStyle.alignment = TextAnchor.UpperCenter;
GUI.Box(new Rect(
Screen.width / 2 - 50 + 20 * level, // <== INDENTATION
Screen.height / 2 - 25, 100, 50),
iteminformation.description, centeredStyle);
}
}
// Process next deeper level
ProcessOnGUI(child, level + 1);
}
}
public class ViewableObject : MonoBehaviour
{
public string displayText;
public bool isInteractable;
}
}
This is the ItemInformation:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemInformation : MonoBehaviour
{
[TextArea]
public string description;
}
Once object is tagged for Interactable and the ItemInformation is attached to it it will display some description for the item.
Now I want to do something for action. For example if the item is Interactable and a script name ItemAction is attached to it do some action, For example move the object from side to side or rotate the object. The logic should be like the Information. It's just with the Action there might be many options then just displaying text.
I'm not sure how to make some logic and how to work with the ItemAction.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemAction : MonoBehaviour
{
}