How can you add a function to a variable. Such as string.ToUpper() ?
I've been programming in C# for about 5 years. However I've always wondered how do you do like below:
public struct Vector3
{
public float X, Y, Z;
}
public Vector3 Positionlol;
void Start()
{
Positionlol.Reset();
}
What do you do to be able to call a function on a variable. I dont want to have to say Reset(Positionlol) and I want to learn how to do it this way, if possible. I assume for example string.ToUpper(); calls a function which operates on the string directly?
I also want to learn this encase I want to create my own type for another crappy engine my university use, which doesn't have things such as Vector3, instead you alter variables as separate floats.
Thanks, Alex
5 years with c# and never came across extension methods? google is your friend... ;)
I know about extention methods. However I don't know how to have it so I could do Vector3 v = new Vector3(0, 10, 0); ?
extension methods answer your first question which was:
"What do you do to be able to call a function on a variable. I dont want to have to say Reset(Positionlol) and I want to learn how to do it this way, if possible. I assume for example string.ToUpper(); calls a function which operates on the string directly?"
for the second part (in future, try to ask each question separately - you're more likely to get timely answers)
Vector3 v = new Vector3(0,10,0);
is perfectly valid in unity - did you try it? any errors?
string is actually System.String, see this stackoverflow answer. You might check out the System.String $$anonymous$$SDN docs to see how they've implemented it. $$anonymous$$eep in $$anonymous$$d though that a string is a reference not a value like a struct is.
Answer by vintar · Jan 12, 2016 at 08:31 PM
You can do something like this I guess :
public static void ResetVector(this Vector3 vector)
{
vector = new Vector3(1, 1, 1);
}
then
Vector3 position = new Vector3(1, 2,3 );
position.ResetVector();
All a bit pointless for vectors, but you get the idea.
Your answer
Follow this Question
Related Questions
How can I change a function from another script? 1 Answer
IEnumerator Not Completing Entire Function 0 Answers
Getting which function affects a GameObject 0 Answers
Function not running everytime 0 Answers
Game highscore file writing 0 Answers