- Home /
Simple Dice Game - Error with Variable within an Instantiated Game Object (Prefab) - CS0118 and CS0119 Errors
Hello Unity Community! Trying to make a simple dice rolling game with two players.
I have an empty game object with the PlayerSetup class attached. The purpose of this script is to create a prefab for each player (2). The prefab has a class attached (as a component) called PlayerDice - within this script it calls the DiceRoll class for each dice that is rolled.
What I am trying to do is pass a value through to the PlayerDice class and change the value of the numDice for each prefab. However, it throws me two errors:
Assets/Scripts/PlayerSetup.cs(31,32): error CS0118: 'PlayerDice' is a 'type' but a 'variable' was expected
Assets/Scripts/PlayerSetup.cs(31,32): error CS0119: Expression denotes a 'type', where a 'variable', 'value' or 'method group' was expected
So clearly something is wrong, I just don't know what. Any thoughts/help? (Below is my code snippets
public class PlayerSetup : MonoBehaviour {
Dictionary<string, int> _PlayerSetup = new Dictionary<string, int>();
public Rigidbody playerPrefab;
void Start () {
//Player Setup
_PlayerSetup.Add("Chad", 4);
_PlayerSetup.Add("Bill", 4);
//Position is not necessary, just doing it for fun
float x = 5;
float z = 5;
//Cycle through the dictionary of players, create them off a prefab
foreach (KeyValuePair<string, int> item in _PlayerSetup)
{
Rigidbody playerInstance;
playerInstance = Instantiate(playerPrefab);
playerInstance.name = item.Key;
playerInstance.GetComponentInChildren<TextMesh>().text = item.Key;
playerInstance.transform.position = new Vector3(x, .5f, z);
playerInstance.GetComponent(PlayerDice).numDice = item.Value;
x = Random.Range(-5, 5);
z = Random.Range(-5, 5);
}
}
}
public class PlayerDice : MonoBehaviour {
public int numDice = 1;
Dictionary<string, List<int>> _PlayerResults = new Dictionary<string, List<int>>();
void Start()
{
//Create a new dice roll
var dice = gameObject.AddComponent<DiceRoll>();
var diceResults = new List<int>();
int num = 0;
int x = 0;
//Rolls a 6 sided dice for each number of dice the player has, stores it into an array
while (num < numDice)
{
x = dice.RollDice(6);
diceResults.Add(x);
Debug.Log("Dice roll: " + diceResults[num]);
num++;
}
Debug.Log("Highest Roll: " + diceResults.Max());
//NOTimplemented yet - I need to pass the item.Key (player name) value through...
//_PlayerResults.Add(item.Key, diceResults);
}
}
public class DiceRoll : MonoBehaviour {
public int RollDice(int diceSides)
{
int result = Random.Range(1, diceSides - 1);
return result;
}
}
Answer by jeffreyrampineda · Nov 23, 2017 at 01:09 AM
In your PlayerSetup class, try this :
playerInstance.GetComponent<PlayerDice>().numDice = item.Value;
instead of this:
playerInstance.GetComponent(PlayerDice).numDice = item.Value;
Your answer
![](https://koobas.hobune.stream/wayback/20220612143205im_/https://answers.unity.com/themes/thub/images/avi.jpg)