Hello!
I would like to reference an object and change one of its variables.
I would like to do this by dragging and dropping things into the script that changes the variables so I can have it change multiple things. I’ve tried using the object and referring to it’s variable as a string, however, I couldn’t figure a way to make this work by unity engine’s reflections.
There may be a way better to just reference the variable (fieldOfView) directly but I’m not sure how to! I know the script will be there alongside the thing I want to change from the beginning. I would really like it if it was in public so I could drag and drop the object and/or write the strings of variables I want to change or the variable itself somehow…
I would like to change other public floats other than the camera (like scripts) so I’ve been really stumped as to how to do it via code.
Thank you!
You can’t really reference variables via the inspector. The only objects you can reference via the inspector are other Unity objects.
Yes you can use some reflection to get said member, but the member name is not actually “Field of View”. It can’t be because that wouldn’t be valid C# code. The variables names we get in the inspector are nice-ified versions of the member’s name. Use the docs to see the real name: Unity - Scripting API: Camera.fieldOfView
Or if it’s a member not publically accessible, use the source code reference: UnityCsReference/Runtime/Export/Camera/Camera.bindings.cs at master · Unity-Technologies/UnityCsReference · GitHub
In any case I’d strongly advise against using reflection.
Tools like the timeline/animation system have ways to reference and modify variables, but this looks like you’re coding a settings system. Honestly it would be less code to just hard-code some of this stuff.
Thank you!
This is a good idea!
For anyone else stumbling over this in the future, I figured out how to do that inflection reflection thing here.
This was the line of code I needed!
Type type = target.GetType();
PropertyInfo prop = type.GetProperty("propertyName");
prop.SetValue (target, propertyValue, null);
floats that you wanna change need {get; set;} to be changed like this.
public float LookSensitivityX { get; set; } = 1f;
public float LookSensitivityY { get; set; } = 1f;