Vision

Can never reach true in the Unmatch at line 71.
mail@pastecode.io avatar
unknown
csharp
a year ago
2.3 kB
7
Indexable
Never
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class Vision : MonoBehaviour
{
    public float viewRadius = 8;
    public LayerMask targetMask;
    public LayerMask obstacleMask;
    public List<Transform> visibleTargets = new List<Transform>();
    public List<Transform> previouslyVisibleTargets = new List<Transform>();

    void Update()
    {
        previouslyVisibleTargets = visibleTargets;
        visibleTargets.Clear();

        Collider[] targetsInViewRadius = Physics.OverlapCapsule(transform.position + (Vector3.up * 10), transform.position - (Vector3.up * 10), viewRadius, targetMask);
        for (int i = 0; i < targetsInViewRadius.Length; i++)
        {
            Transform target = targetsInViewRadius[i].transform;
            Vector3 targetFlatPos = new Vector3(target.position.x, transform.position.y, target.position.z);
            Vector3 dirToTarget = (targetFlatPos - transform.position).normalized;
            float dstToTarget = Vector3.Distance(transform.position, targetFlatPos);

            if (!Physics.Raycast(transform.position, dirToTarget, dstToTarget, obstacleMask))
            {
                visibleTargets.Add(target);
            }
        }

        for (int i = 0; i < visibleTargets.Count; i++)
        {
            if (Match(i, previouslyVisibleTargets))
            {
                visibleTargets[i].GetComponent<MeshRenderer>().enabled = true;
            }
        }

        for (int i = 0; i < previouslyVisibleTargets.Count; i++)
        {
            if (Unmatch(i, visibleTargets))
            {
                previouslyVisibleTargets[i].GetComponent<MeshRenderer>().enabled = false;
            }
        }
    }

    bool Match(int x, List<Transform> pVT)
    {
        for (int i = 0; i < pVT.Count; i++)
        {
            if (pVT[i] == visibleTargets[x])
            {
                return true;
            }
        }
        return false;
    }

    bool Unmatch(int x, List<Transform> vT)
    {
        for (int i = 0; i < vT.Count; i++)
        {
            if (vT[i] == previouslyVisibleTargets[x])
            {
                return false;
            }
        }
        return true;
    }
}