diff --git a/core/array.cpp b/core/array.cpp
index 056ee332f10..08cdec7323a 100644
--- a/core/array.cpp
+++ b/core/array.cpp
@@ -31,6 +31,7 @@
#include "array.h"
#include "core/hashfuncs.h"
+#include "core/math/math_funcs.h"
#include "core/object.h"
#include "core/variant.h"
#include "core/vector.h"
@@ -407,6 +408,10 @@ Variant Array::pop_front() {
}
return Variant();
}
+Variant Array::pick_random() const {
+ ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
+ return operator[](Math::rand() % _p->array.size());
+}
Variant Array::pop_at(int p_pos) {
if (_p->array.empty()) {
diff --git a/core/array.h b/core/array.h
index 09aed83981d..2fcfc4ba813 100644
--- a/core/array.h
+++ b/core/array.h
@@ -72,6 +72,7 @@ public:
void fill(const Variant &p_value);
Variant front() const;
+ Variant pick_random() const;
Variant back() const;
Array &sort();
diff --git a/core/variant_call.cpp b/core/variant_call.cpp
index e57e6bde059..db2a4671425 100644
--- a/core/variant_call.cpp
+++ b/core/variant_call.cpp
@@ -578,6 +578,7 @@ struct _VariantCall {
VCALL_LOCALMEM2(Array, insert);
VCALL_LOCALMEM1(Array, remove);
VCALL_LOCALMEM0R(Array, front);
+ VCALL_LOCALMEM0R(Array, pick_random)
VCALL_LOCALMEM0R(Array, back);
VCALL_LOCALMEM2R(Array, find);
VCALL_LOCALMEM2R(Array, rfind);
@@ -1960,6 +1961,7 @@ void register_variant_methods() {
ADDFUNC1NC(ARRAY, NIL, Array, remove, INT, "position", varray());
ADDFUNC1NC(ARRAY, NIL, Array, erase, NIL, "value", varray());
ADDFUNC0R(ARRAY, NIL, Array, front, varray());
+ ADDFUNC0R(ARRAY, NIL, Array, pick_random, varray())
ADDFUNC0R(ARRAY, NIL, Array, back, varray());
ADDFUNC2R(ARRAY, INT, Array, find, NIL, "what", INT, "from", varray(0));
ADDFUNC2R(ARRAY, INT, Array, rfind, NIL, "what", INT, "from", varray(-1));
diff --git a/doc/classes/Array.xml b/doc/classes/Array.xml
index 8ca08eae8a3..5e9f692dadb 100644
--- a/doc/classes/Array.xml
+++ b/doc/classes/Array.xml
@@ -263,6 +263,16 @@
Returns the minimum value contained in the array if all elements are of comparable types. If the elements can't be compared, [code]null[/code] is returned.
+
+
+
+ Returns a random value from the target array.
+ [codeblock]
+ var array: Array[int] = [1, 2, 3, 4]
+ print(array.pick_random()) # Prints either of the four numbers.
+ [/codeblock]
+
+