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?
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();
}
}