How do I create a player with variables?
Hello Unity!
I am very new to Unity. I do have some experience in C#, but I'm a little rusty, as it's been quite a while!
I want to create a player, with a given name, and for example starting gold, so I made a prefab for this:
public class Player : MonoBehaviour
{
private string name; // field
public string Name // property
{
get { return name; }
set { name = value; }
}
private float gold; // field
public float Gold // property
{
get { return gold; }
set { gold = value; }
}
now my problem comes when I want to instantiate the player. (there won't ever be the need to move around, as there won't be a physical player in the game. I figured I'd need a PlayerManager script, which would instantiate the player, and also update the players properties?
public class PlayerManager : MonoBehaviour
{
Player myPlayer = new Player();
// Start is called before the first frame update
void Start()
{
// Load the player
myPlayer.Name = "Bob";
myPlayer.Gold = 10;
myPlayer.givePlayerStatus(myPlayer.Name, myPlayer.Gold);
}
public string getGold()
{
return "You have " + myPlayer.Gold + " Gold";
}
I created an empty object Gamemanager, and one for Player Manager, but I get a NullReference exception for my GameManager:
public class GameManager : MonoBehaviour
{
Text Goldtext;
PlayerManager myPlayerManager;
// Start is called before the first frame update
void Start()
{
// load the player via playerManager
PlayerManager myPlayerManager = new PlayerManager();
}
// Update is called once per frame
void Update()
{
string output = myPlayerManager.getGold(); //NullRefefenceException here
Goldtext.text = output;
}
}
I'm sure I'm missing one step here somewhere, but I can't just figure it out yet, and I've watched half a dozen tutorials, but they're mostly only covering movement etc.
What am I missing?
Thanks!
Your answer
Follow this Question
Related Questions
Player animation FSM stopped working 0 Answers
Unity editor Slowness when starting 0 Answers
Using LookAt to look at a Vector3 not Transform 0 Answers
Problem Instantiating a Prefab 1 Answer
Problem instantiating projectiles 1 Answer