Unity 数组中对比是否含有某个元素
时间: 2023-07-08 10:17:24 浏览: 81
在 Unity 中,可以使用 `Array.Exists` 方法来判断一个数组中是否存在满足某个条件的元素。具体用法可以参考下面的示例代码:
```csharp
using UnityEngine;
using System;
public class Example : MonoBehaviour
{
void Start()
{
// 定义一个包含一些整数的数组
int[] numbers = { 1, 3, 5, 7, 9 };
// 判断数组中是否存在一个偶数
bool exists = Array.Exists(numbers, n => n % 2 == 0);
if (exists)
{
Debug.Log("数组中存在一个偶数");
}
else
{
Debug.Log("数组中不存在偶数");
}
}
}
```
运行上面的示例代码,如果数组中存在一个偶数,则会输出 "数组中存在一个偶数";否则会输出 "数组中不存在偶数"。
相关问题
Unity 数组中查找是否含有某个元素
在 Unity 中,可以使用 `Array.IndexOf` 方法来查找一个数组中是否包含某个元素,并且返回该元素在数组中的索引位置。如果数组中不包含该元素,则返回 -1。具体用法可以参考下面的示例代码:
```csharp
using UnityEngine;
using System;
public class Example : MonoBehaviour
{
void Start()
{
// 定义一个包含一些字符串的数组
string[] strings = { "apple", "banana", "orange", "pear" };
// 查找数组中是否包含字符串 "orange",并返回其索引位置
int index = Array.IndexOf(strings, "orange");
if (index != -1)
{
Debug.Log("数组中包含字符串 'orange',索引位置为 " + index);
}
else
{
Debug.Log("数组中不包含字符串 'orange'");
}
}
}
```
运行上面的示例代码,如果数组中包含字符串 "orange",则会输出它在数组中的索引位置;否则会输出 "数组中不包含字符串 'orange'"。
Unity 数组中查找是否包涵某个元素
在 Unity 中,可以使用 `Contains` 方法来判断一个数组是否包含某个元素。具体用法可以参考下面的示例代码:
```csharp
using UnityEngine;
public class Example : MonoBehaviour
{
void Start()
{
// 定义一个包含一些整数的数组
int[] numbers = { 1, 2, 3, 4, 5 };
// 判断数组中是否包含数字 3
if (numbers.Contains(3))
{
Debug.Log("数组中包含数字 3");
}
else
{
Debug.Log("数组中不包含数字 3");
}
}
}
```
运行上面的示例代码,如果数组中包含数字 3,则会输出 "数组中包含数字 3";否则会输出 "数组中不包含数字 3"。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)