Trevn Jones
Trevn Jones

Reputation: 333

Unity how to detect if a specific Game Object is near you

I'm creating a test game because I'm getting ready to create my first game but I want to make sure I get all the simple mechanics down that my first game will require. One of the mechanics that will be included in the game is picking up items if they are a certain distance to you. Sometimes there might be multiple of the same object in the game, I figured the code would work for all coins however that is just not the case. The Debug.Log() only works on one specific coin, how do I make it so it will fire no matter what coin I'm near? Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PlayerController : MonoBehaviour {
    //Player Variables
    public float moveSpeed;
    public float jumpHeight;
    public float raycastDistanceGround;
    public Text moneyText;


    private bool isGrounded;
    private Rigidbody _rgb;
    private GameObject player;
    private GameObject[] coin;
    private float distanceToCollectCoin;
    private float distanceToCoin;




    void Start () {
        moveSpeed = 7f;
        jumpHeight = 9f;
        raycastDistanceGround = 0.5f;


        isGrounded = true;
        _rgb = GetComponent<Rigidbody>();
        player = GameObject.FindGameObjectWithTag("Player");
        coin = GameObject.FindGameObjectsWithTag("Coin");
        distanceToCollectCoin = 2f;

        Cursor.lockState = CursorLockMode.Locked;
    }

    void FixedUpdate () {
        IsGrounding();
        Move();
        Jump();
        SetMoneyText();
        NearCoin();

    }

    //Player Moving Mechanics
    void Move() {
        var moveHorizontal = Input.GetAxis("Horizontal") * moveSpeed * Time.fixedDeltaTime;
        var moveVertical = Input.GetAxis("Vertical") * moveSpeed * Time.fixedDeltaTime;

        transform.Translate(moveHorizontal, 0f, moveVertical);

        if (Input.GetKeyDown(KeyCode.Escape)) {
            Cursor.lockState = CursorLockMode.None;
        }
    }

    //Player Jump Mechanics
    void Jump() {
        var jump = new Vector3(0f, _rgb.position.y, 0f);

        if (Input.GetKey(KeyCode.Space) && isGrounded == true) {
            for (float i = 0; i <= jumpHeight; i++) {
                jump.y += i;
                _rgb.AddForce(jump);
            }
        }
    }

    void IsGrounding() {
        if (Physics.Raycast(transform.position, Vector3.down, raycastDistanceGround)) {
            isGrounded = true;
        } else {
            isGrounded = false;
        }
    }

    void SetMoneyText() {
        moneyText.text = ("Money: " + EconomyController.Money);
    }

    void NearCoin() {
        for (int i = 0; i < coin.Length; i++) {
            distanceToCoin = Vector3.Distance(coin[i].transform.position, player.transform.position);

        }

        if (distanceToCoin < distanceToCollectCoin) {
            Debug.Log("Near Coin");
        }
    }
}

Upvotes: 0

Views: 2772

Answers (1)

ryeMoss
ryeMoss

Reputation: 4333

Looks like you just bracketed some stuff wrong. You need to move your if-statement into the for-loop. Right now it's only checking the distance for the last coin in the array.

void NearCoin() 
{
    for (int i = 0; i < coin.Length; i++) 
    {
        distanceToCoin = Vector3.Distance(coin[i].transform.position, player.transform.position);

        if (distanceToCoin < distanceToCollectCoin) 
            Debug.Log("Near Coin");
    }
}

Upvotes: 1

Related Questions