I just started learning and I’m trying to test out some JSON stuff to use later and I have no idea what I’m doing wrong. Unity gives me: error CS1519: Invalid token ‘=’ in class, struct, or interface member declaration These lines specifically. Code (CSharp): starter.name = "Boomer"; starter.health = 10; starter.attack = 1; Code (CSharp): public class Creature{ public string name; public int health,attack; } Creature starter = new Creature(); starter.name = "Boomer"; starter.health = 10; starter.attack = 1; string json = JsonUtility.ToJson(starter);
That code looks fine, so I'm guessing it's related to something else. Try posting the entire script, along with the line number the error is occurring on. You'll notice that the compiler error will tell you the line number.
Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Main : MonoBehaviour { public GameObject MainMenu; public GameObject BattleMenu; public Button tester; public void SceneSwitch2Battle(){ MainMenu.SetActive(false); BattleMenu.SetActive(true); } public class Creature{ public string name; public int health,attack; } Creature starter = new Creature(); starter.name = "Boomer"; starter.health = 10; starter.attack = 1; string json = JsonUtility.ToJson(starter); } The error says: Assets\Main.cs(28,16): error CS1519: Invalid token '=' in class, struct, or interface member declaration Then it says the same thing two other times for lines 29 and 30.
As @APSchmidt says, the Creature starter = new Creature(); statement needs to go inside of a method. Right now you just have it directly within the class, which isn't allowed. That could go in Start() or Awake(), or you could create a new method and place that code in it. The next question is, are you planning on reusing the "starter" object many times? If so, you'd want to make it a private class variable, and then assign it a value in Start() or Awake().