- Home /
Random role assigning from string array
Simple enough : I have a system in place where I have a list of roles, cops /robbers, which is assigned in the inspector in the form of a string. How can I write a script which randomly assigns all agent a role, either cops or robbers , every time I start a new game?
Answer by Legend_Bacon · Jul 18, 2018 at 02:15 PM
Hello there,
This should give you what you need.
Put this script on any object in your scene, and in the inspector set:
• The number of Robbers
• The number of Cops
• A list of agents (you can name them if you like), with a count equal to the sum of the two numbers above.
Then run the game, and you'll get a list of Agents with a name and a random role.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DistributeRolesClass : MonoBehaviour
{
// Serialized so you can view and edit it in the inspector
[System.Serializable]
public class Agent
{
public string agentName = "";
private string agentRole = "";
public string GetAgentRole()
{
return agentRole;
}
public void SetAgentRole(string newAgentRole)
{
agentRole = newAgentRole;
}
}
public List<Agent> list_agents = new List<Agent>();
// The sum of these 2 must be equal to the length of "list_agents"
[Space]
[Header("• Game Settings")]
[SerializeField] private int i_numberOfRobbers = 0;
[SerializeField] private int i_numberOfCops = 0;
public void Start()
{
DistributeRoles();
}
private void DistributeRoles()
{
List<string> roles = new List<string>();
for (int i = 0; i < i_numberOfRobbers; i++)
roles.Add("Robber");
for (int i = 0; i < i_numberOfCops; i++)
roles.Add("Cop");
foreach (Agent agent in list_agents)
{
string role = roles[Random.Range(0, roles.Count)];
roles.Remove(role);
agent.SetAgentRole(role);
}
}
}
I hope that helps!
Cheers,
~LegendBacon
Thanks a million but I was more looking for guidance in the form documentation as I already have a script to work with. This will certainly help though.
You know this:
private string agentRole = "";
public string GetAgentRole()
{
return agentRole;
}
public void SetAgentRole(string newAgentRole)
{
agentRole = newAgentRole;
}
is basically this:
public string AgentRole { get; set; }
Yes, but there's a high chance they would also want to do something else in that Set() call, and it's much prettier to do it this way :)
Your answer
Follow this Question
Related Questions
(c#) display a random string at game over 2 Answers
Can I create a list with an int/float and a string? C# 2 Answers
Pick between two floats 2 Answers
How to fix some of location have more than 1 object? 2 Answers