I am programming the backend of a multiplayer game for a school project. I need to load a random document (more specifically a user's username) from a collection of users. That part works. Basically, I run into an issue where the username stays null ("") when I call the function, instead of the username that should be loaded with the docRef.get() function. Below is the code that I wrote, however I've found that it doesn't only happen with this function, but with all the ones that use the docRef.get() function.
Any help would be much appreciated, as I've been stuck on this issue for over a week. It's my first project in Kotlin/Firebase.
Thanks.
fun getRandomPlayerUsername() : String{
var db = FirebaseFirestore.getInstance() // Loads Firebase functions
var loadedPlayer:LoadedPlayer? = null
val random = (0 until 3).random()
val docRef = db.collection("users").orderBy("username").limit(3)
var username:String = ""
docRef.get().addOnSuccessListener { documentSnapshot ->
val playerList: MutableList<out LoadedPlayer> = documentSnapshot.toObjects(LoadedPlayer()::class.java)
loadedPlayer = playerList[random]
username = loadedPlayer?.username.toString()
}
return username
}