sombat92
sombat92

Reputation: 109

Unity C# Error: "Type or namespace definition, or end-of-file expected"

I have tried many times to fix this without success. Whenever I close my function on line 14 (public void FrenchButton ()), it thinks it closes public class LanguageMenuScript : MonoBehaviour. How can I fix this?

The code is below:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class LanguageMenuScript : MonoBehaviour
{
    public Text languageTitleText;

    public void FrenchButton()
    {
        public string language = "French";
    }


    void Start (){
        Text.text = Language;
    }

    void Update()
    {
        if (language == "French")
        {
            languageTitleText.text = "Langue";
        }

    }


}

Upvotes: 0

Views: 604

Answers (2)

leo Quint
leo Quint

Reputation: 787

You have public string language = "French"; inside a function. You can't have a access modifier inside a function and you cant access variables declared inside a function from outside. What you want to do there is declare it next to languageTitleText inside the class scope. you can then assign a value in your FrenchButton function if you want -> language = "French"; for instance.

Upvotes: 2

Domi
Domi

Reputation: 24528

Solution 1

Use a proper internationalization package. You are making yourself a lot more work than you'd like using your current approach. This concept (usually using I18n) and its application to Unity is discussed here.

Solution 2: Fixing your code

You probably want to use an enum, like below. Once you have changed the script, check out the component in the inspector. You can now choose from the given set of languages defined in your enum.

Here is an official tutorial on how to use enums in Unity.

Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public enum Language {
  French: 1,
  German: 2,
  English: 3
}

public class LanguageMenuScript : MonoBehaviour
{
    public Text languageTitleText;
    public Language language = Language.French;

    void Start (){
    }

    void Update()
    {
        if (language == Language.French)
        {
            languageTitleText.text = "Langue";
        }
        else if (language == Language.German) 
        {
            languageTitleText.text = "Sprache";
        }
        else
        {
          // take English as default
          languageTitleText.text = "Language";
        }
    }
}

Upvotes: 1

Related Questions