0
\$\begingroup\$

This might be more of a general C#/programming query, but since it's game dev related, I'm putting it here.

I am trying to randomise a property in a custom component (C# script) across several Unity game objects.

hostiles is a list of game objects, each with an attached Stats component.

foreach (GameObject gO in hostiles)
{
    // Randomise spawn area…
    gO.GetComponent<Stats>().AreaNo = Random.Range(0, 3);
}

Perhaps unsurprisingly, all of my objects end up with the same value for AreaNo. It seems as though I’m reassigning some global version of Stats.AreaNo in my loop, rather than the individual instances. What am I missing?

(Sorry in advance for the noobish question!)

\$\endgroup\$
5
  • \$\begingroup\$ 1. How is the variable/property AreaNo of the Stats class declared? 2. where exactly is the snippet you posted executed? \$\endgroup\$
    – Philipp
    Mar 26, 2016 at 21:07
  • \$\begingroup\$ 1. The Stats class only consists of a private variable called _areaNo, and a property AreaNo w/getter & setter. Stats is attached to the game object prefabs that are instantiated & held in the hostiles list. 2. The snippet is in the Start method of a script called SpawnManager. \$\endgroup\$ Mar 27, 2016 at 14:27
  • \$\begingroup\$ Your mistake is likely somewhere in that code. Please edit your question and add it. \$\endgroup\$
    – Philipp
    Mar 27, 2016 at 16:50
  • \$\begingroup\$ Thanks Philipp. That helped me find where the issue was. My hostiles list contained references to a prefab, rather than instances of it. Hence I was reassigning the same component property every pass of the loop. \$\endgroup\$ Mar 27, 2016 at 17:23
  • \$\begingroup\$ But I didn't even do anything. Next time before you ask a question on stackexchange, you might want to try this proven debugging technique first. \$\endgroup\$
    – Philipp
    Mar 27, 2016 at 17:38

1 Answer 1

1
\$\begingroup\$

My bad. My hostiles list contained references to a prefab, rather than instances of it. Hence I was reassigning the same component property every pass of the loop.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .