How do I use get and set in C#? - c#

I know that this is a pretty obvious question but from what I've seen I can't yet get it.
I don't exactly understand how Getters and Setters work in C#, for instance, I have this code for a character in a game I'm supposed to make for college:
namespace Clase_25_3_2014
{
class Brick
{
private int speed { get; set; }
private Vector2 pos { get; set; }
private Texture2D skin { get; set; }
public Brick(int speed, Vector2 position, Texture2D skin)
{
this.Speed(speed);
this.Pos(position);
this.Skin(skin);
}
}
}
Now, as it stands, where I use the class I try to call it like this:
Brick brick = new Brick(1, Vector2.Zero, mySkin);
brick.GetPos();
Now, obviously that looks weird for you guys, and that's because I haven't yet found out how am I supposed to use it correctly so that it works like a brick.getPos(); from java.
Sorry for the really obvious question, but I can't seem to find an answer for me.

You can't do GetPos because pos is private and you don't have a method called "GetPos". If you make pos public, you can just use Brick.pos to get and Brick.pos(position) to set.
Here's how you could write this class:
namespace Clase_25_3_2014
{
class Brick
{
public Brick(int speed, Vector2 position, Texture2D skin)
{
this.Speed = speed;
this.Pos = position;
this.Skin = skin;
}
public int Speed { get; set; }
public Vector2 Pos { get; set; }
public Texture2D Skin { get; set; }
}
}
Types of Class access:
// lots of explicity (is that a word? :)
public MyClass
{
// Field
// It is recommended to never expose these as public
private int _myField;
// Property (old school, non-auto private field)
public int MyProperty
{
public get
{
return this._myField;
}
public set
{
this._myField = value;
}
}
// Property (new school, auto private field)
// (auto field cannot be accessed in any way)
public int MyProperty2 { public get; private set; }
// Method (these are not needed to get/set values for fields/properties.
public int GetMyMethod()
{
return this._myField;
}
}
var myClass = new MyClass;
// this will not compile,
// access modifier says private
// Set Field value
myClass._myField = 1;
// Get Property Value
var a = myClass.MyProperty;
// Set Property Value
myClass.MyProperty = 2;
// Get Property Value
var b = myClass.MyProperty2;
// this will not compile
// access modifier says private
// Set Property Value
myClass.MyProperty2 = 3;
// Call method that returns value
var c = myClass.GetMyMethod();

When you declare an auto-property in C#, it will get compiled behind the scenes into get and set methods, but you do not need to even think about those. You can access the property as if it were a field.
The benefit of having the property is that you can easily swap it out for a more conventional property with a backing field so that you can provide custom logic in the getter and/or setter. Until you need that, however, it is just extra noise. The auto-property provides the syntactic sugar to avoid that noise.
Brick brick = new Brick(1, Vector2.Zero, mySkin);
Vector2 oldPos = brick.pos;
brick.pos = new Vector2.One;

Try changing to this:
public Brick(int speed, Vector2 position, Texture2D skin)
{
this.Speed = speed;
this.Pos = position;
this.Skin = skin;
}
And with C# you don't need this type of constructors. You can declare an object of this class without constructor with the following way:
public Brick brickTest(){
Speed = 10,
Position = new Vector2(),
Skin = new Texture2D()
};

namespace Clase_25_3_2014
{
class Brick
{
public int Speed { get; set; }
public Vector2 Pos { get; set; }
public Texture2D Skin { get; set; }
public Brick(int speed, Vector2 position, Texture2D skin)
{
this.Speed = speed;
this.Pos = position;
this.Skin = skin;
}
}
}
Using outside:
Brick brick = new Brick(1, Vector2.Zero, mySkin);
Console.WriteLine(Brick.Pos);
however, Behind the scenes the compiler create for each Property:
Private variable storage of the Property-type.
Two function (Get\Set).
Translate the property used to their Functions.

You should just do:
Brick brick = new Brick(1, Vector2.Zero, mySkin);
Vector2 vec = brick.pos;

Related

Unity. How to store generic data for usage in ScriptableObject's code (different NPC types)

I have a bunch of different kind of NPCs in my game and of course they logically similar, they have health, they have vision, they can navigate using agent and stuff.
But each NPC type has it's own custom behavior with states, actions, decisions and hooks. And those scripts require various specific data like coroutines running, target altitude or current leaping direction.
And I have to store it or have it on NPC mono behavior, so it is accessible inside state's scripts (they are scriptable objects called from NPC mono behavior)
Right now what I do is specifying array for each data type and count of it that I assign on NPC prefab. And it feels wrong...
public class Npc : MonoBehaviour
{
public static Dictionary<int, Npc> npcs = new Dictionary<int, Npc>();
public int npcId;
public NpcType type;
public Transform shootOrigin;
public Transform head;
public float maxHealth = 50f;
public float visionRange = 15;
public float visionAngle = 60;
public float headAngle = 120;
public float movementSpeed = 4.5f;
public int indexedActionsCount = 0;
[HideInInspector] public float[] lastActTimeIndexed;
[HideInInspector] public bool[] wasActionCompletedIndexed;
public int indexedVector3DataCount = 0;
[HideInInspector] public Vector3[] vector3DataIndexed;
public int indexedFloatDataCount = 0;
[HideInInspector] public float[] floatDataIndexed;
public int indexedBoolDataCount = 0;
[HideInInspector] public bool[] boolDataIndexed;
public int indexedCoroutineDataCount = 0;
[HideInInspector] public IEnumerator[] coroutineDataIndexed;
public NpcState currentState;
public NpcState remainState;
public float Health { get; private set; }
[HideInInspector] public NavMeshAgent agent;
public static int decisionUpdatesPerSecond = 2; // Check for decisions in 2FPS
public static int actionUpdatesPerSecond = 5; // Act in 5FPS
public static int reportUpdatesPerSecond = 15; // Report in 15FPS
private static int nextNpcId = 10000;
public void Awake()
{
agent = GetComponent<NavMeshAgent>();
}
public void Start()
{
npcId = nextNpcId;
nextNpcId++;
npcs.Add(npcId, this);
Health = maxHealth;
agent.speed = movementSpeed;
lastActTimeIndexed = new float[indexedActionsCount];
wasActionCompletedIndexed = new bool[indexedActionsCount];
floatDataIndexed = new float[indexedFloatDataCount];
boolDataIndexed = new bool[indexedBoolDataCount];
vector3DataIndexed = new Vector3[indexedVector3DataCount];
coroutineDataIndexed = new IEnumerator[indexedCoroutineDataCount];
ServerSend.SpawnNpc(npcId, type, transform.position);
InvokeRepeating("GetTarget", 1.0f, 1.0f);
InvokeRepeating("UpdateDecisions", 0.0f, 1.0f / decisionUpdatesPerSecond);
InvokeRepeating("UpdateActions", 0.0f, 1.0f / actionUpdatesPerSecond);
InvokeRepeating("SendUpdates", 0.0f, 1.0f / reportUpdatesPerSecond);
OnEnterState();
}
public void TakeDamage(float _damage)
{
}
public bool GoTo(Vector3 location)
{
}
public void TransitionToState(NpcState nextState)
{
OnExitState();
currentState = nextState;
OnEnterState();
}
public void StartCoroutineOnNpc(IEnumerator routine)
{
StartCoroutine(routine);
}
public void StopCoroutineOnNpc(IEnumerator routine)
{
StopCoroutine(routine);
}
private void OnEnterState()
{
var hooks = currentState.onEnterHooks;
for (int i = 0; i < hooks.Length; i++)
{
hooks[i].Apply(this);
}
stateTimeOnEnter = Time.time;
wasActionCompleted = false;
}
private void OnExitState()
{
var hooks = currentState.onExitHooks;
for (int i = 0; i < hooks.Length; i++)
{
hooks[i].Apply(this);
}
}
private void UpdateDecisions()
{
currentState.UpdateDecisions(this);
}
private void UpdateActions()
{
currentState.UpdateState(this);
}
private void SendUpdates()
{
ServerSend.NpcState(this);
}
}
In JavaScript world I would just have 1 array or object and put any data this particular NPC needs to it. But in C# I need a strongly typed place to put data for each data type my scripts could require.
Example of data usage in script:
I don't think having so many arrays and counters on MonoBehavior is a good idea, especially that there may be a lot of NPCs on scene. Any advice on building better storage while maintaining script flexibility?
Clarification:
All the behavior logic is controlled by flexible ScriptableObject states. The problem is these objects cannot store any runtime data, but they have access to my Npc MonoBehavior (component) instance.
Initial code for this approach came from Unity tutorial
Let me explain the structure I ended up using for the case I described:
If particular NPC requires some specific data for its behavior I will add another component (in this example leaper NPC needs to store data for leaping behavior)
This data is defined in interface (it's important, because 1 NPC may implement multiple interfaces [several reused behaviors])
public interface ILeaperData
{
public Vector3 leapTarget { get; set; }
public Vector3 initialPosition { get; set; }
public bool startedLeap { get; set; }
public float lastLeapTime { get; set; }
}
And then this NPC type will have component that implements this interface (and 1 more in this example)
public class LeaperData : NpcData, ILeaperData, ICompletedActionData
{
public Vector3 leapTarget { get; set; }
public Vector3 initialPosition { get; set; }
public bool startedLeap { get; set; }
public float lastLeapTime { get; set; }
public bool wasActionCompleted { get; set; }
}
That way I can reuse data interfaces when the same behavior is used on other NPC types.
Example of how it is used in ScriptableObject logic:
[CreateAssetMenu(menuName = "AI/Decisions/CanLeap")]
public class CanLeapDecision : NpcDecision
{
public int nextAngle = 45;
public float radius = 4;
public override bool Decide(Npc npc)
{
if (npc.target)
{
var dir = (npc.transform.position - npc.target.position).normalized;
var dir2 = new Vector2(dir.x, dir.z).normalized * radius;
var dir3 = new Vector3(dir2.x, dir.y, dir2.y);
if (NavMesh.SamplePosition(RotateAroundPoint(npc.target.position + dir3, npc.target.position, Quaternion.Euler(0, nextAngle * ((Random.value > 0.5f) ? 1 : -1), 0)), out var hit, 3.5f, 1))
{
var path = new NavMeshPath();
npc.agent.CalculatePath(hit.position, path);
if (path.corners.Length == 2 && path.status == NavMeshPathStatus.PathComplete)
{
((ILeaperData)npc.npcData).leapTarget = hit.position;
((ILeaperData)npc.npcData).initialPosition = npc.transform.position;
((ILeaperData)npc.npcData).startedLeap = false;
return true;
}
}
}
return false;
}
private Vector3 RotateAroundPoint(Vector3 point, Vector3 pivot, Quaternion angle)
{
var finalPos = point - pivot;
//Center the point around the origin
finalPos = angle * finalPos;
//Rotate the point.
finalPos += pivot;
//Move the point back to its original offset.
return finalPos;
}
}
You can see the cast to (ILeaperData) where I need the data stored on this NPC instance.

How to distinguish between different objects using an interface

I'm creating a platform system using a raycast controller that uses an interface to perform different tasks based on the type of platform with which my player is currently colliding. Some of the platform types include ice, passable blocks and muddy ground.
I want to know how to better optimize my code, as I currently call Unity's somewhat expensive "GetComponent()" function every frame, even if I never change between blocks. What I'd like to do is only call GetComponent() when I change from one type of platform to a different type of platform (i.e. muddy ground --> ice), but don't know how to do this using an interface.
I thought I would be able to compare types using enums, but you're not allowed to declare types in an interface.
if (hit)
{
//I'd only like to run this block of code if the type of platform changes
var platform = hit.collider.gameObject.GetComponent<IPlatform>();
State.IsCollidingWithPassablePlatform = platform.IsPassable;
State.IsJumpBoosted = platform.IsJumpForce;
State.IsBoosted = platform.IsForce;
xForce = platform.XForce;
yForce = platform.YForce;
zForce = platform.ZForce;
defaultParameters.accelerationTimeGrounded = platform.AccelerationTimeGrounded;
defaultParameters.accelerationTimeAirborne = platform.AccelerationTimeAirborne;
Interface example:
interface IPlatform {
float AccelerationTimeGrounded { get; }
float AccelerationTimeAirborne { get; }
float XForce { get; }
float YForce { get; }
float ZForce { get; }
bool IsPassable { get; }
bool IsForce { get; }
bool IsJumpForce { get; }
Ice platform:
public class PlatformIce : MonoBehaviour, IPlatform {
public float AccelerationTimeGrounded { get { return accelerationTimeGrounded; } }
public float AccelerationTimeAirborne { get { return accelerationTimeAirborne; } }
public float XForce { get { return xForce; } }
public float YForce { get { return yForce; } }
public float ZForce { get { return zForce; } }
public virtual bool IsPassable { get { return false; } }
public bool IsForce { get { return false; } }
public bool IsJumpForce { get { return false; } }
[SerializeField]
private float accelerationTimeGrounded = 1.0f;
[SerializeField]
private float accelerationTimeAirborne = 3.0f;
private float xForce = 0;
private float yForce = 0;
private float zForce = 0;
}
Remember your last GameObject and check if this one has changed
private lastGameObj;
[...]
if(lastGameObj!= hit.collider.gameObject) {
var platform = hit.collider.gameObject.GetComponent<IPlatform>();
// [...] your magic here
lastGameObj= hit.collider.gameObject;
}
You will get an additional condition, but you won't run your code 60 times/sec inclusive that GetComponent();.
You CAN use enums inside an Interface, you just have to declare the enum type outside the Interface.
I.E.:
public enum PlatformType {Normal, Ice, Fire, etc}; //Use public only if needed, of course
interface IPlatform {
PlatformType platformType { get; }
//Your other stuff here
}
This will break encapsulation, clearly, but if you really want to use an enum in an interface, there's no way around it.

Unity C# Custom class in dictionaries

So yeah, i feel really dumb to ask this question, but i'm currently in the process of writing a simple pathfinder script. I want to use dictionaries like
Dictionary<Floor, FloorInfo>
where floor is the floor tile i am referencing and FloorInfo is custom class as follows:
public class FloorInfo
{
Floor lastFloor;
float floorValue;
public FloorInfo(Floor lastF, float val)
{
lastFloor = lastF;
floorValue = val;
} }
But after i create something like
FloorInfo info = new FloorInfo(current, F);
I cannot get the values, like info.val or info.lastF
Could you explain to me what am I doing wrong? I feel really awkward that i got stuck on something like that or past 45 minutes.
EDIT: Okay, thank you everyone who already answered. Seems like most obvious things can be quite problematic as well. Thanks again and have a nice day!
Make them public if you want to access them from outside the class.
You must mark the fields lastFloot and floorValue as public, or better yet provide a public property for accessing those private fields, like this:
public class FloorInfo
{
private Floor m_lastFloor;
private float m_floorValue;
public Floor LastFloor {
get { return m_lastFloor; }
}
public float FloorValue {
get { return m_floorValue }
}
public FloorInfo(Floor lastF, float val)
{
m_lastFloor = lastF;
m_floorValue = val;
}
}
Then you can access the values like this:
FloorInfo info = new FloorInfo(current, F);
float value = info.FloorValue;
The lastF and val are parameters to your constructor. These are gone as soon as the constructor completes.
You have copied these values to lastFloor and floorValue but currently they are private. You should make these public. If you dont specify a modifier then by default it is private and is not visible outside of the class that they are defined.
public class FloorInfo
{
public Floor lastFloor;
public float floorValue;
public FloorInfo(Floor lastF, float val)
{
lastFloor = lastF;
floorValue = val;
}
}
so you can then reference info.floorValue and info.LastFloor
If you want good design then you should make these into properties and possibly make the set private so they it cannot be changed outside of the FloorInfo class. Also make the properties start with capital letters.
public class FloorInfo
{
public Floor LastFloor { get; private set; }
public float FloorValue { get; private set; }
public FloorInfo(Floor lastF, float val)
{
lastFloor = lastF;
floorValue = val;
}
}
That is because C# class' field's access modifier (by default) is private. What you do above is trying to access private field outside of the scope of the class (which is not allowed).
To access the fields, make its access modifiers public, then you can access them outside of the class scope:
public class FloorInfo
{
public Floor lastFloor; //note the public keyword
public float floorValue;
public FloorInfo(Floor lastF, float val)
{
lastFloor = lastF;
floorValue = val;
}
}
And simply access the fields like:
FloorInfo info = new FloorInfo(current, F);
info.lastFloor = new Floor();
info.floorValue = 45.0;
Note that you do not access the lastF and val from above since they are simply your constructor's parameters. You access the fields of your class, not its constructor's parameters.
That being said, it is more common to access them as property rather than field.
public Floor lastFloor { get; set; }
public float floorValue { get; set; }
This is because with property, you could set something else in your getter and setter (such as checking if the inputs for your property is valid), which is, most of the time, a safer design:
const float floorValueLimit = 20.0;
private float pFloorValue;
public float floorValue {
get { return pFloorValue; }
set {
if (value <= floorValueLimit){ //check limit
pFloorValue = value;
} //else, don't update
}
}
But you cannot do this using field.
Also, as an additional side note, public field would normally have capital letter as its first character in C# typical naming convention:
public class FloorInfo
{
public Floor LastFloor; //note the public keyword
public float FloorValue;
public FloorInfo(Floor lastF, float val)
{
lastFloor = lastF;
floorValue = val;
}
}

c# how do I do a private set property?

I am creating a VECTOR object like so, but I am initializing it in the constructor:
public VECTOR position { get; private set; }
I am doing this operation:
position.x += 2;
VECTOR has a variable x defined as:
public double x { get; set; }
I get the error when I do the +=2 operation that says:
Cannot modify the return value of 'Projectile.position' because it is
not a variable
I want to be able to modify the position vector in the current class, and I want it to be accessible but not modifiable in other classes.
Probably, your problem is with the Vector class actually being a struct. Assume you have the following declarations:
public class Projectile
{
public VECTOR position { get; private set; }
public Projectile()
{
position = new VECTOR();
}
}
public struct VECTOR
{
public double x {get; set;}
}
You cant edit properties of the position property directly because you are accessing a copy of that field (explained here).
If you don`t want to convert your VECTOR into a class you can add a method that updates the position of your projectile:
public void UpdatePosition(double newX)
{
var newPosition = position;
newPosition.x = newX;
position = newPosition;
}
That will create a copy of the position, then update its x property and override the stored position. And the usage would be similar to this:
p.UpdatePosition(p.position.x + 2);
Expose the X property (and others) of VECTOR in a class.
public class myObject {
private VECTOR position;
public double X { get{return position.x;}set{position.x=value;}}
}
Usage example:
myObject.X += 2;

Why doesn't GraphicsHeight exist in my Game class?

I really need help on this so please be patient.
Alright, so I've recently started to work on my first game, very basic.
I decided to create a GameObject class. That will contain the basics of my other classes (e.g : Player, Enemies).
So, this is the currently code of the GameObject class:
abstract class GameObject
{
GraphicsDevice gr;
Vector2 position;
Texture2D texture;
public GameObject(Vector2 Position, Texture2D Texture)
{
this.position = Vector2.Zero;
this.texture = Texture;
}
public Vector2 Position { set; get; }
public Texture2D Texture { set; get; }
public float X
{
set { position.X = value; }
get { return position.X; }
}
public float Y
{
set
{
position.Y = value;
}
get
{
return position.Y;
}
}
public int GraphicsWidth { set; get; }
public int GraphicsHeight { set; get; }
}
OK, so I wanted to set the GraphicsWidth and GraphicsHeight variables from the Main Class (Game1.cs) so in the Initialize method I've done this:
GraphicsHeight = graphics.PreferredBackBufferHeight;
GraphicsWidth = graphics.PreferredBackBufferWidth;
But it says that GraphicsHeight doesn't exist in the current context.
I know I'm missing something but I don't know what.
BTW, Is there anything wrong or anything that I can do better with my GameObject class?
Thanks a lot.
You must have another, concrete class inherit your abstract GameObject. For instance:
public class Player : GameObject
{
/* methods properties specific to player */
}
After instantiation, you will then be able to set those properties:
Player.GraphicsHeight = graphics.PreferredBackBufferHeight;
Player.GraphicsWidth = graphics.PreferredBackBufferWidth;

Categories