- Home /
C# - Lists containing Functions and Random.Range
So I'm having trouble wrapping my head around how to select randomly from a list of functions. I've tried googling but the keyword 'list' seems to throw off my results from what I'm after. Basically what I'm trying to achieve is having a list of possible functions, and then starting one of them randomly.
The idea behind this is I have a enemy that doesn't move, but has a range of attack animations that I want to be randomly selected and played out, for example, maybe it does attack one, or attack two, etc.
Here's the code I've started:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class bosscontrols : MonoBehaviour {
delegate void bossMoves();
void CreateList()
{
List<bossMoves> moves = new List<bossMoves>();
moves.Add(idle);
moves.Add(attackOne);
moves.Add(attackTwo);
moves[0]();
}
void Update () {
//Do I somehow use Random.Range here to pick from my listed functions?
}
void idle ()
{
//play idle animation here
}
void attackOne ()
{
//play attackOne animation here
}
void attackTwo ()
{
//play attackTwo animation here
}
}
What I can't figure out is how exactly to refer to the listed options with Random.Range (I assume that's what I would use)..
Thanks for any help you can offer!
Answer by gjf · Apr 12, 2016 at 01:21 PM
moves[Random.Range(0, moves.Count)]();
but you'll need to make sure you define moves
in the right scope (i.e. NOT in CreateList()
)
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Pick between two floats 2 Answers
Random element from the list 1 Answer