public class Rule : MonoBehaviour{} Rule rule2 = new Rule();
You cannot use the new keyword to create a new instance if you inherit from MonoBehaviour .
You should get an exception that says:
You are trying to create MonoBehaviour using the 'new' keyword. It is forbidden. MonoBehaviours can only be added using AddComponent (). Also, your script can inherit from ScriptableObject or no base class at all
Your code would work if you had a public class Rule {} , but you have a public class Rule : MonoBehaviour {} .
Create a new instance of the class derived from MonoBehaviour :
Class Example:
public class Rule : MonoBehaviour { public Rule(int i) { } }
If you inherit from MonoBehaviour , you must either use GameObject.AddComponent or Instantiate to create a new instance.
Rule rule2 = null; void Start() { rule2 = gameObject.AddComponent<Rule>(); }
OR
public Rule rulePrefab; Rule rule2; void Start() { rule2 = Instantiate(rulePrefab) as Rule; }
If the Rule script already exists and is attached to the GameObject, you do not need to create / add / create an instance of a new instance of this script. Just use the GetComponent function to get the script instance from the GameObject to which it is attached.
Rule rule2; void Start() { rule2 = GameObject.Find("NameObjectScriptIsAttachedTo").GetComponent<Rule>(); }
You will notice that you cannot use the parameter in the constructor when outputting the script from MonoBehaviour .
Creating a new instance of the class that is NOT derived from MonoBehaviour :
Class example: (Please note that it does not come from " MonoBehaviour "
public class Rule { public Rule(int i) { } }
If you do not inherit from MonoBehaviour , you should use the new keyword to create a new instance. Now you can use the parameter in the constructor if you want.
Rule rule2 = null; void Start() { rule2 = new Rule(3); }
EDIT
In the latest version of Unity, creating a new instance of the script that inherits from MonoBehaviour with the new keyword may not give you errors and may not be null either, but all callback functions will not be executed. They include the functions Awake , Start , Update and others. So you should still do it right, as indicated at the beginning of this answer.