Home > Net >  How do I interact with objects?
How do I interact with objects?

Time:05-21

My Query

I am just learning Unity and I haven't been able to find comprehensive guide on how to interact with objects in a top down game.

My Solution

I have used the following code to create a radius for an object, in which you are able to interact with the said object, however I have no idea how to put the plan in motion. I have seen people use PlayerController, but I am not sure I should use it with RigidBody. Here's my Interactable.cs:

using UnityEngine;

public class Interactable : MonoBehaviour
{
    public float radius = 1.0f;

    private void OnDrawGizmosSelected() {
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, radius);
    }
}

What I need help with

Could someone point me in the right direction on how to interact with an object when player is inside the radius, on an example of removing the object?

CodePudding user response:

This code solves your problem. You must inject the player instance at the beginning of each Interactable object. Then it is enough to measure the distance through Vector.Distance. Definitely a shorter distance is in the range.

private GameObject player;
public float radius = 1.0f;
public void OnEnable() => player = GameObject.FindWithTag("Player");
public void Update()
{
    var distance = Vector3.Distance(player.transform.position, transform.position);
    if (distance <= radius)
    {
        Debug.Log("Player is range of: " name);
    }
}

Also remember that you have specified the player tag.

enter image description here

  • Related