So the first thing I want to see is if my ray understands that my key is an interactable, but I do this via the interface, for example check if the whole object is type IInteractable
and if it is run the Interact
function.
When I do it on the door, it works, but when in the key, it doesn't; I don't understand why (I did a thorough search for it but I still can't find a solution). Also when I try to interact with the key it always shows me the debug.log("none")
I put in my ray script.
PS: I put the the interface from my ray script to another script to be more clear but it still doesn't change anything in case you tell me that I commented out the interface
ray script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// interface IInteractable
// {
// public void Interact();
// }
public class Interactor : MonoBehaviour
{
[SerializeField] private Transform InteractorSource;
[SerializeField] private float interactRange = 5f;
// public bool active = false;
// Update is called once per frame
void Update()
{
Ray r = new Ray(InteractorSource.position, InteractorSource.forward);
// Debug.DrawRay(r.origin, r.direction * 10);
if (Input.GetKeyDown(KeyCode.E))
{
// active = Physics.Raycast(r, out RaycastHit hitInfo, interactRange);
// out hitInfo
if (Physics.Raycast(r, out RaycastHit hitInfo, interactRange))
{
if (hitInfo.collider.gameObject.TryGetComponent(out IInteractable interactObj))
{
Debug.Log("interacted");
interactObj.Interact();
}else Debug.Log("none");
}
}
}
}
Key script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Key : MonoBehaviour, IInteractable
{
// [SerializeField] private GameObject door;
public void Interact()
{
Debug.Log("key");
// gameObject.SetActive(false);
// door.GetComponent<DoorScript>().SetHasKey(true);
}
}
Door script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorScript : MonoBehaviour, IInteractable
{
private bool haskey = false;
public void Interact()
{
// Debug.Log("hello that's a door");
if (haskey)
{
gameObject.transform.GetComponent<Animator>().SetTrigger("Activate");
}
}
public bool GetHasKey()
{
return haskey;
}
public void SetHasKey(bool newHasKey)
{
haskey = newHasKey;
}
}
I expected a debug.log("key")
but instead I got debug.log("none")
hitInfo
is in fact giving you the "key". That version of the raycast function only gives you the first hit, so if that ray hits something else first, you might not get the object you expect.