You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity课程中C#匿名函数排序逻辑疑问:actionValue减法实现排序的原理解析

Understanding the Sort Logic in Your Enemy AI Code

Great question! Let's break down exactly how that anonymous function is sorting your EnemyAIAction list by actionValue—it's all about how C#'s List.Sort() method uses comparison delegates.

How List.Sort() Uses the Comparison Delegate

First, let's recap the core rule that List.Sort() follows when you pass it a comparison function (like your anonymous lambda):

  • If the function returns a negative number, the first parameter (a) should come before the second parameter (b) in the sorted list.
  • If the function returns 0, the order of a and b doesn't matter (they're considered equal for sorting purposes).
  • If the function returns a positive number, the second parameter (b) should come before the first parameter (a) in the sorted list.

Breaking Down Your Anonymous Function

Your sorting line looks like this:

enemyAIActionList.Sort( (EnemyAIAction a, EnemyAIAction b) => b.actionValue - a.actionValue );

Let's translate this into plain language with concrete numbers to make it clear:

Suppose we have two EnemyAIAction instances:

  • a has an actionValue of 5
  • b has an actionValue of 10

When we calculate b.actionValue - a.actionValue, we get 10 - 5 = 5 (a positive number). Following the Sort() rules, this tells the method to place b before a—so the higher value comes first.

Another example:

  • a has an actionValue of 8
  • b has an actionValue of 3

Here, 3 - 8 = -5 (a negative number). This tells Sort() to place a before b—keeping the higher value first.

If both values are equal (e.g., a.actionValue = 6, b.actionValue = 6), the result is 0, so their relative order stays as-is.

Putting this all together, your lambda function sorts the list in descending order of actionValue—highest values at the top of the list, lowest at the bottom.

Why This Works for Your Enemy AI Use Case

Since you're trying to find the best enemy AI action, sorting by actionValue in descending order makes perfect sense: the first item in the sorted list will be the action with the highest value (your "best" action). I assume your method will end with something like return enemyAIActionList[0]; to grab that top result!

内容的提问来源于stack exchange,提问作者James MacDonald

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:07:31