Hi everyone, I’m implementing an interface for interactable objects, and I’m struggling with calling a method on those objects when the player interacts with them. I created a script for the interface with :
public interface IInteractable{
void Interact();
}
My interactable objects have the method implemented and “, IInteractable” after MonoBehaviour in their class definition, for example :
public class AntennaController : MonoBehaviour, IInteractable
{
private bool isRepaired = false;
[SerializeField] private UnityEvent Repair;
public void Interact()
{
if (!isRepaired)
{
Repair.Invoke();
isRepaired = true;
}
}
}
And here is the Interactor script on the player :
public class Interactor : MonoBehaviour
{
private IInteractable interactable;
private void Update()
{
if (Input.GetButtonDown("Interact") && interactable != null)
{
Debug.Log("interact");
interactable.Interact();
}
}
private void OnCollisionEnter(Collision collision)
{
// if we collide with an interactable
if(collision.gameObject.GetComponent<IInteractable>() != null)
{
interactable = collision.gameObject.GetComponent<IInteractable>();
Debug.Log(interactable != null);
}
}
}
the debug.log in OnCollisionEnter return true (so interactable is supposed to not be null), but the debug.log in the if statement (in the Update method) never shows (which means interactable would be null). If I don’t check that interactable is not null again, I have a NullReferenceException with interactable.Interact()
I’m very confused about that and really don’t know how to fix it. I’ve followed multiple tutorials doing exactly the same but I can’t make it work. I’ve also read about null checking being different for interface component but I didn’t find a solution.
If anyone can help, that would be much appriciated