Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

unity3d - Unity Script C#, Array to list, How to Optimize object detection in a better way?

I'm working on RTS game and need a better way for units to deter each other.

When each unit is doing this, at around 30 units this starts to become very expensive way to run things.

What would be a better way to optimize this:

private void Update()
{
 if(target == null) 
        {
            ArrayDetect();
            AttackUnit();
            return;  
        }

[SerializeField] private Collider[] colliderArray;
    [SerializeField] private List<GameObject> enemyColliders;


   
    private void ArrayDetect()
    {
       colliderArray = Physics.OverlapSphere(ownAimAtPoint.position, fireRange, layerMask);
       
       
       foreach (Collider collider in colliderArray)
        {
                Debug.Log("we hit a", collider);                if(!collider.TryGetComponent<Targetable>(out Targetable potentialTarget)) 
                {
                    return;                   
                }    
                if (potentialTarget.hasAuthority)
                    {     
                    return;  
                    }
                
                else
                {
                enemyColliders = enemyColliders.Distinct().ToList();
                enemyColliders.Add(collider.gameObject);
                Debug.Log("Found an enemy", potentialTarget);
                }                
        }
    }

Physics.OverlapSphere to find colliders in range with layermask tag, then sort through them and add them to a enemy List then:

private void AttackUnit()
    {
        //if (enemyColliders.Count == 0) { return; }

        foreach (GameObject enemy in enemyColliders)
        {
         Debug.Log("We got confirmed enemy", enemy);
gameObject.GetComponent<Targeter>().CmdSetTarget(enemy);
                //attack the enemy

        }
        
    }

go through enemy List and assign each enemy as a target to attack.

question from:https://stackoverflow.com/questions/65908498/unity-script-c-array-to-list-how-to-optimize-object-detection-in-a-better-way

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...