- Home /
Get and Set difference
What's the difference between doing this
public byte getCurrentMoves(){
return currentMoves;
}
public void setCurrentMoves(byte info){
currentMoves = info;
}
And doing this?
public byte CurrentMoves {
get { return currentMoves; }
set { currentMoves = value; }
}
Besides length of code, why is or isn't the second way better?
Answer by whydoidoit · Feb 13, 2014 at 04:18 AM
The second method lets you make a property that looks like a variable:
CurrentMoves = 1; //Calls the set method
print(CurrentMoves); //Calls the get method
Obviously the first way is more wordy and doesn't look like a normal field:
setCurrentMoves(1);
/ can you also help me with my script ***receiving error "; expected" and get/set does not exist in the current context
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CameraFollow : $$anonymous$$onoBehaviour { private Transform player; private float damping = 2f; private float height = 7f; private Vector3 startPos; private bool canFollow;
// Start is called before the first frame update
void Start()
{
player = GameObject.FindWithTag("Player").transform;
startPos = transform.position;
canFollow = true;
}
// Update is called once per frame
void Update()
{
Follow();
}
void Follow()
{
if (canFollow)
{
transform.position = Vector3.Lerp(transform.position, new Vector3(player.position.x + 10f, player.position.y + height, player.position.z - 10f), Time.deltaTime * damping);
}
}
public bool CanFollow() { get { return canFollow; } set { canFollow = value; }
}
} // class
Don't post questions in comments to other questions. If you have a concrete and specific question, ask a seperate question. Anyways, remove the method brackets from your property declaration. It's a property, not a method.
So it should be
public bool CanFollow { get ...........
ins$$anonymous$$d of
public bool CanFollow() { get ...........
Answer by poncho · Feb 13, 2014 at 05:00 AM
The difference between methods and properties, is just to the programmers, methods mean actions, while properties mean... well, properties, a description or feature of something. to your immediate example would be like getCurrentMoves() would mean, getting the info of the variable currentMoves, and setCurrentMoves would mean, setting the bytes to currentMoves variable, which does not feels quite right, on the other hand, if you use it as a property (which could be just public byte CurrentMoves{get;set;}), it implies that you will get and set values to the CurrentMoves property. I think i could not explain myself well enough, but hope you get something from my explanation
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Getters/Setters with C# Array 1 Answer
Getter / Setter and Variable Scope Question? 1 Answer
Semi Generic With References 0 Answers