-1
\$\begingroup\$

This is bizarre enough that it has to be me being an idiot.

I have a MonoBehaviour with some public fields and public methods:

public class MyComponentA : MonoBehaviour
{
    public string Message = "Foobar";
    public int Integer = 42;

    public string GetMessage() => "This is a message.";
    public int GetInteger() => 42;
}

I've added it to a prefab called Circle_A.

Circle_B has a MonoBehavior that will instantiate an instance of Circle_A, get the component and log out the values returned from the fields and the methods:

public class CircleB : MonoBehaviour
{
    [SerializeField] private GameObject _circleAPrefab;

    private void Start()
    {
        var circleAInstance = Instantiate(_circleAPrefab, new Vector2(10, 10), Quaternion.Euler(Vector3.zero),transform);
        var myComponentA = circleAInstance.GetComponent<MyComponentA>();
        var message = myComponentA.Message;
        LogIt(message);
        LogIt(myComponentA.GetMessage());
        LogIt(message);
        Log(myComponentA.Integer);
        Log(myComponentA.GetInteger());
    }

    private static void LogIt(string message)
    {
        switch (message)
        {
            case null:
                Log("NULL");
                return;
            case "":
                Log("EMPTY");
                return;
            default:
                Log($"'{message}'");
                return;
        }
    }
}

The integer field and both the methods return as expected, the number 42 and the messageThis is a message. The message field however is always an empty string.

What's happening?

\$\endgroup\$
0
\$\begingroup\$

I checked your code, it's working. Select the prefab with a double click - it is possible that you have emptied the value of Message for the prefab in the Inspector of Circle_A.

\$\endgroup\$
  • \$\begingroup\$ If I had emptied it then I would be getting a NullReferenceException when I called the members. \$\endgroup\$ – BanksySan Oct 9 at 18:56
  • \$\begingroup\$ Now I understand what you're saying and, you're totally right. The UI was overriding the hard coded values. Thank you. I was going mad. \$\endgroup\$ – BanksySan Oct 9 at 18:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.