Initialize script component added to gameobject dynamically.

I found many questions on the same topic and all of them mention this line:

Beam beamScript = beamCenter.AddComponent<Beam>() as Beam;

In this case I have a script called Beam.cs

The problem I face is not all variables inside are intilized so when i press play I get an error, “Object not set to an instance” aka null pointer exception. I have this code so far creating my new game object dynamically:

GameObject beamCenter = new GameObject("beamCenter");
LineRenderer beam = beamCenter.AddComponent<LineRenderer> () as LineRenderer;
BezierSpline spline = beamCenter.AddComponent<BezierSpline> () as BezierSpline;
Beam beamScript = beamCenter.AddComponent<Beam>() as Beam;
beamScript.startPoint = startPoint;
beamScript.endPoint = endPoint;
beamScript.startWidth = 0.1f;
beamScript.endWidth = 0.1f;
beamScript.planetCenter = planet.transform.position;

Maybe the order of initialization is wrong but is this the right way to initialize variables inside a script component?
Or how would a skilled Unity programmer do this?

In your Beam class you can use the RequiredComponent attribute and Unity will automatically add those components whenever your Beam component is added.

For your properties that always have the same default constant value you can use an initializer, for example in your beam class declaration…

class Beam {
  public float startWidth = 0.1f;
}

Whenever you create an instance of your Beam class the startWidth property will default to 0.1. Additional initialization can take place in Beam’s Start method.

Another thing you can do to help with initialization code is to create a static method in the class to create an instance and do some initialization that’s difficult to do in other places, e.g…

static public GameObject Create(Vector2 startPoint, Vector2 endPoint, Vector2 planetCenter)
{
    GameObject beamCenter = new GameObject("beamCenter");

    // add the script - I'm assuming you've made the other changes
    // so some things will already be initialized
    Beam beamScript = beamCenter.AddComonent<Beam>() as Beam; 

    beamScript.startPoint = startPoint;
    beamScript.endPoint = endPoint;
    beamScript.planetCenter = planetCenter;

    return beamCenter;
}

You’d call this like so:

GameObject beamCenter = Beam.Create(startPoint, endPoint, planet.transform.position);

It might make more sense for Beam.Create to just add the Beam script to a passed in game object instead of creating the game object itself - kind of depends on your needs. In that case you’d potentially just return the Beam script instead of the GameObject, but again that depends on your needs.

Depending on how complex this gets, you could also set this all up in a prefab and instantiate that, then initialize the fields you need to, but I’d most likely still do that in a static function somewhere.