A custom class in Unity C#

So, the thing is…
I’ve got my own class called Vehicle. Now I have to make an instance of that class into an actual game object which I can trasnlate, scale and so on. I don’t need anything fancy, I just want to slap some sprite onto that instance and move it around the scene. It doesn’t have to be that exact class though, anything works. How do I do that, guys? Thanks

public class Vehicle
{
public int id;
public string name;
public TilesPosition tilesPosition;
public Vector2 actPosition;
public Directions direction;
public Vector2 actDestination;
public TilesPosition tilesDirection;
public object
public Vehicle()
{ }

public Vehicle(int id, string name, TilesPosition tilesPos, Vector2 actPosition, Directions direction, Vector2 actDestination = new Vector2(), TilesPosition tilesDirection = new TilesPosition())
{

this.id = id;
this.name = name;
this.tilesPosition = tilesPos;
this.actPosition = actPosition;
this.direction = direction;
this.actDestination = actPosition;
this.tilesDirection = tilesPos;
}

}

There’s two ways of doing it:

  • Change your class so that it inherits from MonoBehaviour. You won’t be able to have a constructor for your class anymore, but you will be able to attach it directly to a game object and have it drive things like position and rotation.
  • Write a separate MonoBehaviour-derived class which creates an instance of your Vehicle class, sends messages to it (like updating it each frame) and taking values from it to feed into a gameObject’s position/rotation/etc.
1 Like

It won’t let me create an instance of a class inheriting from MonoBehaviour. I get the idea. I just really hoped for some example in code. Does the first option make my class static or something?

How are you trying to create an instance of your MonoBehaviour-derived class?

1 Like

via new

You can’t do that. MonoBehaviours must always be attached to GameObjects, which means you have to create them either via the Editor (adding them as a component) or by calling GameObject.AddComponent().

1 Like

okay, so

GameObject plane = Instantiate(Resources.Load(“plane”), new Vector3(0,0), UnityEngine.Quaternion.identity) as GameObject;

plane.AddComponent();

something like that?

Okay, I got it. Thanks so much for your help.