I have a script that looks like this:
using UnityEngine;
using System.Collections;
//Moves object in a fixed direction and speed.
public class FixedVelMover : Mover {
public float speed, direction; // direction is in degrees, starting from right, counterclockwise
private Rigidbody2D rigidbody;
// Use this for initialization
void Start () {
rigidbody = GetComponent<Rigidbody2D> ();
float directionRad = direction * Mathf.Deg2Rad;
rigidbody.velocity = new Vector2(Mathf.Cos(directionRad), Mathf.Sin(directionRad)) * speed;
}
public FixedVelMover (float speed, float direction) {
this.speed = speed;
this.direction = direction;
}
}
But when I try to use the constructor with something like
FixedVelMover mover = new FixedVelMover (1f, 270);
I get an error message saying that I can’t create a MonoBehaviour using the ‘new’ keyword. It suggests AddComponent, but if I do that, I can’t choose the speed and direction when initializing, and setting the speed and direction at runtime does nothing.
Components (MonoBehaviours) do not let you have access to the constructors, you would need to approach the situation differently.
A MonoBehaviour is meant to be attached to a GameObject so you will need to have an object available to attach it to, a simple example code will be as follows:
public void createMover()
{
// Create a new object
GameObject obj = new GameObject();
// Attach a new instance of your component to the object and store it in 'mover'
FixedVelMover mover = obj.AddComponent<FixedVelMover>();
// Call a method which can initialize the data values on the object
mover.initialize(speed, direction);
}
You would need to have an initialize method but It’s not that much harder to do this than it is to use a normal constructor. With your current setup however, you might run into an issue where your object runs the Start method before your Initialize method so it may behave unexpectedly.
I really do just suggest that instead of using a constructor behaviour, you could create a prefab and use the editor to adjust these values instead.