- Home /
C# String Requires Manual Assignment in Inspector
My String variable stringText keeps requiring that I manually assign it in the Inspector. If I don't then it's left blank and my save function saves a blank string. It should be automatically assigning to a value like with Floats and Strings. Any idea how I could get around this?
using UnityEngine;
using UnityEngine.Events;
public class UserSettingString : MonoBehaviour
{
public string stringText { get; set; }
public UserSettingEventString onSettingLoaded;
void OnEnable()
{
Load();
}
public void Load()
{
onSettingLoaded.Invoke(stringText = PlayerPrefs.GetString(name));
}
public void Save()
{
PlayerPrefs.SetString(name, stringText);
}
}
[System.Serializable]
public class UserSettingEventString : UnityEvent<string>
{
}
Answer by NewPath · Oct 17, 2015 at 08:31 PM
You'll need to make it a field, not a property for it to work correctly in the inspector. The inspector cannot properly serialize properties.
What exactly do you mean? I already have a field for both my UserSettingEventString Class and my string stringText in my main UserSettingString class.
public class UserSettingString : $$anonymous$$onoBehaviour
{
public string stringText { get; set; }
public UserSettingEventString onSettingLoaded;
No, you don't have a field, you have declared an auto property called stringText. onSettingLoaded is an actual field / variable but stringText is not.
Declare it like this:
public string stringText;
edit
In case you don't know what a property is read this and this.
Ok I've made stringText into a field. But now I can't select stringText in a UnityEvent field within the inspector. How do you serialize stringText without turning it into a property? You can't declare a variable outside of a class and you can't put [System.Serializable] inside of a class.
Edit: I did find [SerializeField] which allowed me to serialize stringText. However I still can't select stringText in a UnityEvent field within the inspector.
Basically the UserSettingString's Script runs through several different GUI gameobjects. I have a total of 4 gameobjects the string test gameobject, change text button, save button and load buttons. The Change Text button changes the text to String Text. The String test gameobject contains the userSettingString Script and is the gameobject that all of the GUIs reference. Save and Load execute their respective functions. I can compress the assets and put them into a unitypackage if necessary. I realize this is a bit difficult since you can't actually see my project.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
How to make a single word in a Text object clickable / have hover. 2 Answers
C# Variable 4 Answers
Can i give GetComponent a variabel instead of a scriptname? 1 Answer