I'm new to C# and I am trying to get the basics under my belt, so far every problem I've ran into has been solved with a quick google search, for some reason this one is just going over my head.
I'm attempting to assign a string to the value that I believe is returned from "Player.Name" from a referenced API.
This is for a game "FiveM"
My Client.net:
string name = Player.Name;
The referenced API:
// Summary:
// Gets the name of this CitizenFX.Core.Player.
public string Name
{
get
{
throw null;
}
}
Reference pics
string name = Player.Name
API
API .Name ref
string to be returned from Player.Name but I continue to get the error "An object reference is required for the non-static field, method, or property 'Player.Name'"
CodePudding user response:
First of all I believe you added the throw null
and that it is not a part of the API. If not then you have to implement the getter.
The reason you get the error An object reference is required for the non-static field, method, or property 'Player.Name'
is because you call the method without an instance of the Player class. You'll have to create a player object at some point by calling the constructor like this var player = new Player()
and then you'll be able to make a call to player.Name
.
The below example shows a working example
public class Player
{
public string Name { get; set; }
}
public class OtherClassThatUsesPlayer
{
public Method()
{
var player = new Player
{
Name = "My Main Character"
};
var name = player.Name;
}
}
This tutorial is a good starting point https://www.w3schools.com/cs/cs_classes.php
CodePudding user response:
The "Player" object is null, therefore there's no way to retrieve the value of the "Name" property, because it doesn't exist, hence the "an object reference is required". "Player" doesn't reference an object.
Much of programming is error handling, and handling issues which aren't normal. I would presume you're expecting Player to be set to something, so your code needs to handle it if it's not.
Also, I would suggest understanding how to set breakpoints in your code using whatever IDE you're using (VS Code or Visual Studio, I would presume) and debug it line by line. You will be able to instantly see that "Player" is null, and you'd be able to look at your call stack to see where it was set (or not set) to find the reason Player is null.
CodePudding user response:
Error is clear that you are trying to access a nonstatic property using the class name itself. you need an object reference for the same, so use the below.
Name
is the property of class Player
.
Player player = new Player();
string name = player.Name;