Home > Software engineering >  slider or a field with a static variable in a script
slider or a field with a static variable in a script

Time:01-27

Hye everyone, I'm a bit lost with the static, Do you know if it is possible to make a slider (or a field) that updates a static variable. The idea behind this is that if I apply a script to several GameObjects and change the value of the slider to one of them, all the sliders in the other scripts are set to the same value. I'm trying to set this up to make it easier to adjust.

Good Day

CodePudding user response:

You can kind of do this modifying the value directly but changes won't be persisted between game runs. That's because Unity doesn't support serializing static vars. So you can only really use it to run some quick tests but on the next run static vars will have their default values.

Try something like this in your inspector code:

staticVal = EditorGUILayout.Slider("some label", staticVal, minVal, maxVal);

Perhaps there could be another way to help with what you what to achieve. Try and extend your question.

CodePudding user response:

Even if you succeed (see e.g. the other answer) ... a static value will not be serialized -> not saved! So actually this doesn't help you anything at all in editor time.

You should consider rather using a ScripableObject instead like e.g.

// See https://docs.unity3d.com/ScriptReference/CreateAssetMenuAttribute.html
[CreateAssetMenu]
public class FloatValue : ScriptableObject
{
    [Range(0, 1)] public float Value;
}

You would create an asset instance of this via ProjectView (Assets)right-clickCreateFloatValue.

Then you can reference this value everywhere where needed e.g.

[SerializeField] private FloatValue myFloat;

and simply drag your asset into this slot.

Special hint: You can make your asset the default reference for any new created instance of your component by directly selecting the according script file within Unity and in the Inspector drag the asset into the according slot. This will make it the default for any new created instance of this component in the editor.

  •  Tags:  
  • Related