Pass a property of a component to another method.
I have an array of prefabs that each have a script attached with a frequency float variable. I want to pass that property from each item in the array into a method that will pick one randomly with more chance for higher frequency items. I can't seem to get it to work.
Here is what I am trying. Any help is appreciated.
public class LetterSpawner : MonoBehaviour{
public float xMin;
public float xMax;
public GameObject[] letterArray;
// Use this for initialization
void Start() {
}
public void SubmiToRandomizer()
{
PickRandom(letterArray[].GetComponent<Letters>().frequency);
}
public float PickRandom(float[] probs)
{
float total = 0;
foreach(float elem in probs)
{
total += elem;
}
float randomPoint = Random.value * total;
for (int i = 0; i < probs.Length; i++)
{
if(randomPoint < probs[i])
{
return i;
}
else
{
randomPoint -= probs[i];
}
}
return probs.Length - 1;
}
Answer by thePeine · Feb 10, 2017 at 02:25 AM
If you want to turn your list of GameObjects into a list of floats, something like the following should work.
At the very top of your file, add the following if it's not already there:
using System.Linq;
then in SubmiToRandomizer:
float[] probs = letterArray.Select( x => x.GetComponent < Letters >().frequency ).ToArray();
PickRandom(probs)
I'm not in front of a compiler, so there might be typos, but something like that should work.
Your answer

Follow this Question
Related Questions
Random Number every 5 seconds 2 Answers
Help with Randomized Sprite on GUI button click 0 Answers
Randomly generate blocks on a flat map 0 Answers
Generate Random sequence of color sprites 0 Answers
Random values not different 2 Answers