using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class FishCollector : MonoBehaviour { public GameObject collectiblesContainer; // Total score of all collectibles public int totalScore = 0; Collectible[] collectibles; Renderer r; CharacterController cc; // Start is called before the first frame update void Start() { r = GetComponent(); cc = GetComponent(); collectibles = collectiblesContainer.GetComponentsInChildren(); } // FixedUpdate is called consistently at 50 fps (by default) // Figured we can do collection checks slightly less frequently :) void FixedUpdate() { Vector3 fishPosition = r.bounds.center; foreach (Collectible collectible in collectibles) { if (collectible.collected || !collectible.isEnabled) { // Skip collectibles already collected or disabled continue; } Renderer collectibleRenderer = collectible.GetComponent(); float collectibleRadius = collectibleRenderer.bounds.extents.magnitude; Vector3 collectiblePosition = collectibleRenderer.bounds.center; bool x = false; bool y = false; bool z = false; // Debug.Log(String.Format("FishPosition: {0}, CollectiblePosition: {1}, CollectibleRadius: {2}", fishPosition, collectiblePosition, collectibleRadius)); // Check if we are colliding with the collectible if (fishPosition.x >= collectiblePosition.x - collectibleRadius && fishPosition.x <= collectiblePosition.x + collectibleRadius) { x = true; } if (fishPosition.y >= collectiblePosition.y - collectibleRadius && fishPosition.y <= collectiblePosition.y + collectibleRadius) { y = true; } if (fishPosition.z >= collectiblePosition.z - collectibleRadius && fishPosition.z <= collectiblePosition.z + collectibleRadius) { z = true; } if (x && y && z) { totalScore += collectible.score; collectible.Collect(); // Assume we aren't colliding with 2 at the same time! break; } } } }