Home > Blockchain >  Interfaces in Game Development Unity 3D
Interfaces in Game Development Unity 3D

Time:08-24

Sorry, I know this is a dumb question but my brain needs some strong methods to help it gets through. I found a video on youtube about Interface => HERE the situation and codes were showed here. And My question:

 private void Update()
        {
            var nearestGameObject = GetNearestGameObject();
            if (nearestGameObject == null) return;
            if (Input.GetButtonDown("Fire1"))
            {
                var interactable = nearestGameObject.GetComponent<IInteractable>();
                interactable?.Interact();
            }
        }

In Update function => this line of code => var interactable = nearestGameObject.GetComponent<IInteractable>();
The GetComponent<IInteractable>(), what actually does it get ? get the interface ???? or get the Game Object, I have never seen an interface attached to the Gobj in the inspector before.

CodePudding user response:

An interface cannot be instantiated. Instead, it will get the interactable object which is an instance of a class that implement IInteractable.

CodePudding user response:

interactable will hold a reference to a Component that implements this interface, interactable will be null if none is found.

Use interfaces in cases where you do not care what component type that is but you want guarantees that you can call some very specific method on it, for example: interactable.Interact().

CodePudding user response:

It will get the component "IInteractable" which you have placed on the nearest object.

  • Related