0

In Unity have a class cars.cs and garage.cs In garage.cs I want to add different objects of car class.

public class Car : MonoBehaviour {
    public int color {get;set;}
    public string name {get;set;}

    public Car(int color, string name){
        this.color      = color;
        this.name       = name ;
    }
}

public class Garage : MonoBehaviour {
    public Car c01 = new Car(1,"BMW");
    public Car c02 = new Car(3,"Honda");
}

Garage.cs is attached to a EmptyObject in Unity. Now I always get the error that it is not allowed to create with "new" keyword. But how else is it possible to set everything/initialize? (color, name) if I do not want to create an empty object in project for each car and attach it by drag and drop?!

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

Thanks you in advance :)

Programmer
  • 121,791
  • 22
  • 236
  • 328

0 Answers0