- Home /
store a reference to a float in a variable? (similar to what the "ref" keyword does)
Hello everyone,
is it possible to store a referece of a float? What i tried (using the "ref" keyword):
List<FloatInfo> backups = new List<FloatInfo>();
public void BackupInt(ref float referenceToFloat, float value) {
backups.Add(new FloatInfo(referenceToFloat, value);
}
...
public class FloatInfo {
public float reference; // Since the "ref" keyword is only available for function parameters i can't do "public ref float referece";
public float value;
public FloatInfo(ref flaot reference, float backupValue) {
// unfortunately this copies the variable instead of using the reference. Therefore the reference is gone :(
this.reference = reference;
this.value = backupValue;
}
}
I need the reference to know what variable i am dealing with. When i need to call a backup i just want to set the int reference equal the backupValue. By that i want to achieve a Undo system.
Hopefully you understand what i want to achieve (It's kind of tricky to explain). Do you have an idea to solve this?
(wrapping the int in a class is not the solution. The reference realy needs to refer to the "origin" float. I want to undo transform.position.x values by that)
Answer by Glurth · Sep 01, 2017 at 05:20 PM
While there is the nullable float option ( float? ), it does not actually store a reference. Though the ref keyword does exactly what you want, it can only be applied to function parameters, not member variables.
Alas, I don't think this is going to be possible, without a wrapper class. (Hopefully, someone will post otherwise.)
That being said, don't forget you have the ability to define IMPLICIT cast to/from float functions, that should allow you to use your wrapper class everywhere you can use a normal float. But even then, if want to keep a reference, rather than a value, you would need to declare the variables you STORE as that wrapper-class, rather than a float. (This obviously excludes the transform.position.x you wanted to use: in this case, you would need to keep the reference to the transform class itself, and somehow, know which member of the transform to use.)
Thank's a lot! I will try to solve this with a wrapper class :)
Answer by Jeshira · Nov 01, 2020 at 12:48 PM
I think Unite Austin 2017 conference about game architecture seems to answer this, and spoiler, with ScriptableObject.
//FloatVariable.cs
[CreateAssetMenu(fileName ="FloatVariable", menuName = "Architecture/Float Variable")]
public class FloatVariable : ScriptableObject {
public float value;
}
//FloatReference.cs
[System.Serializable]
public class FloatReference {
public bool useConstant = true;
public float constant;
public FloatVariable variable;
public float Value => (useConstant)
? m_constant : m_variable.value;
}
Right, that's what Glurth meant by "wrapper class". I can also highly recommend this Unite talk.