Just a few class related questions.

So I’ve been doing some OO in Visual Studio using C# and have decided to try my hand at classes in Unity but have come across a few issues.

Firstly - “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
UnityEngine.MonoBehaviour:.ctor()”

That is the warning I get when I try to initialize a class, here is my code to initialize -

	public Transform myTransform;
	
	// Use this for initialization
	void Awake () {

       ClassTest imATest = new ClassTest("Donkey", "Fish", "Mule", "Meow", myTransform);
    }

Here is the actual class -

public class ClassTest : MonoBehaviour {
	
	private string animal1;
	private string animal2;
	private string animal3;
	private string sound;
	private Transform myTransform;
	
	//Constructor
	
	public ClassTest(string animal1, string animal2, string animal3, string sound, Transform myTransform)
	{
		this.animal1 = animal1;
		this.animal2 = animal2;
		this.animal3 = animal3;
		this.sound = sound;
		this.myTransform = myTransform;
	}

Now, thats only a warning but I get an actual error when I try to instantiate the transform in a method. - Only assignment, call, increment, decrement, and new object expressions can be used as a statement

Here is my method for the instantiation -

public void Spawn()
	{
		Instantiate(myTransform, gameObject.Find(spawnArea).transform.position, Quaternion.identity) as Transform;	
	}

Obviously I’m very new at all this so any help would be much appreciated!

Cheers.

I am only seeing two problems:

public class ClassTest : MonoBehaviour {

//later
ClassTest imATest = new ClassTest(...);

Classes that inherit from MonoBehaviour have certain restrictions placed on them. One of them is that you cannot use the keyword “new” to create a MonoBehaviour class. If you want to create an instance of the class without attaching it to a GameObject in the process, use

public class ClassTest {

And now you are working with a pure class, with no restrictions: just like old times.

Second Problem:

Instantiate(...) as Transform;
  1. Instantiate returns a GameObject, not a Transform. If you want the transform, refer to returnedGameObject.transform

  2. You are not storing the variable anywhere after it is cast. The problem is that compiler reads the line as [Pseudo code!]

    call Method(), then cast as Object
    cast [result] as Object
    Object
    //Computers do something, but “Object” is not a verb,
    //so what do you want the computer to do? It doesn’t know. Error!

There are two easy was to fix. You can simply add an assignment so that the Object is used

assign something to Object

Or you can remove the cast at the end so that the computer will read the line as

call Method()