Get And Set problem

Hi, im not familiar with getters and setters. I’m trying to implement it in my script. But when I try to acces the variable I get this Warning and the variabe Im trying to acces doesn’t change.

The code I’m trying to acces:

public class FFAOpMovement : MonoBehaviour {

	private float xPos;
	public float XPos{
		get { return xPos; }
		set { xPos = value; }
	}

	// Use this for initialization
	void Start () {

	}
	
	// Update is called once per frame
	void Update () {
		Debug.Log (xPos);
	}
}

Trying to acces the code with:

public class toolTest : MonoBehaviour {

	FFAOpMovement ffaop = new FFAOpMovement();

	// Use this for initialization
	void Awake () {
		ffaop.XPos = 3f;
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}

The warning i get:

You are trying to create a MonoBehaviour using the ‘new’ keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all

Read the error message. You can’t make MonoBehvaiour objects using the new keyword, which is what you tried to do in the second code segment. The message even gives you a suggestion of how to fix it.

Why can’t you do this? Because of the structure of Unity. Unity attaches scripts to GameObjects. In doing so, it allows the underlying engine to access those scripts and run the various built-in methods like the Update loops. The reason you can’t make one with the new keyword (e.g. new Script()) is because you never specify what it should be attached to - it’s not part of any GameObject. Unity cannot access the built-in methods now, and so there’s no purpose to it being a MonoBehaviour in the first place (since that’s the only benefit you get from that).

Instead of this, Unity offers the AddComponent method, which allows you to attach a new component to a specified GameObject. This means you specify which object the script is attached to, and so Unity can access it, because it is part of the scene. Unity can’t arbitrarily hop around your code looking for every MonoBehaviour you’ve instantiated - it needs you to put it in the scene, attached to a GameObject.

I suggest, in future, you actually read the errors and warnings you get. When programming, they are one of the most helpful tools you will get for solving problems.