C# is getting an empty array using random numbers

daidaikeai0816 注册会员
2023-02-26 15:10

Part of this answer refers to GPT, GPT_Pro to solve the problem better.
C# encountered an empty situation when obtaining an array using random numbers. This is a common problem. When Random.Range() is used to obtain random numbers, null may occur. This is usually because Random.Range() returns an integer between the specified range, but if the array is not long enough, some positions may be empty.

Here is an example to better understand the problem: Suppose we have an array of type int[] with four elements, then when we use Random.Range(0,4) to get a random number, the return value could be any of 0,1,2, or 3, but never greater than 3, so we get a null value when we try to access index 4.

To solve this problem, we can use a while loop to iterate through each element in the group until we find one that is not null. For example:

int[] array = new int[4]; 
// 假设已有4个元素全部不为null

int index = Random.Range(0, array.Length); 
// 获取随机数 0123中的任意一个

while (array[index] == null) 
    index = Random.Range(0, array.Length); 
// 如果当前位置的元素为null则重新获取随机数并重新检查

// 输出不为null的元素

If the answer is helpful, please accept it.

About the Author

Question Info

Publish Time
2023-02-26 15:10
Update Time
2023-02-26 15:10