I'm trying really hard to get a grip on Unity and C#, I was using a tutorial example from Okita's book, and apparently the "new" keyword can't be used to create Monobehaviours: fair enough, I substituted it with MyThis mt = gameObject.AddComponent<MyThis>(); but now when I press play (code is attached to main camera) it keeps looping the print commands (as if it were in the Update function, but it's not!) Can anyone help me get my head around this? Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class MyThis : MonoBehaviour { float MyFloat; public void AssignMyFloat(float f) { MyFloat = f; } public void ShowMyFloat() { Debug.Log(MyFloat); } public void AssignThisMyFloat(float MyFloat) { this.MyFloat = MyFloat; //using the this keyword, we can be sure that the variable is assigned to a class variable, // and not something only in the function. // The this keyword in only necessary when the name of a parameter in a function matches the variable in a class // where the function's parameter appears. ß //Debug.Log(MyFloat); print("I'm working"); } // class MyAwkwardClass // { // int MyBadlyNamedInt = 0; // void PoorlyNamedFunction () // { // Debug.Log (this.MyBadlyNamedInt); // int MyBadlyNamedInt = 7; // Debug.Log (this.MyBadlyNamedInt); // } // // } // Use this for initialization void Start() { MyThis mt = gameObject.AddComponent<MyThis>(); mt.AssignMyFloat(3.0f); mt.ShowMyFloat(); mt.AssignThisMyFloat(5.0f); mt.ShowMyFloat(); } }
Any new component that you create will automatically Awake, Start, and do all that other stuff that components ordinarily do (assuming the GameObject it's attached to is active). So when you create a new MyThis component, that new component will Start, which will create a new MyThis component, which will Start, which will create a new MyThis component, etc.
Thank you so much for answering! So it seems this tutorial wasn't really very well done in that case. Does this mean that I should take the cut the contents of start and plop them in a different script and then call the class MyThis?
I haven't seen the tutorial, but I imagine they put the code for creating the new object inside a function that doesn't run automatically every time an object of that type is created (or possibly added some sort of condition to it). I can't really tell you where to put the code, because I'm not sure what you're trying to accomplish with this. If your goal is just for it to run once when the program starts, you could put it in the Start function of some other MonoBehaviour (so that the class being created isn't the same as the class doing the creation).
Ok, just tried making another script with the contents of the start function (after removing them from MyThis) and calling the MyThis class from there in the start function of the other script component. Thank you so much for your help, I wouldn't have understood otherwise!