• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by spinnerbox · Oct 06, 2015 at 12:27 PM · gameobjectaddcomponentinitializationscript compilation error

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?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Dave-Carlile · Oct 06, 2015 at 12:49 PM

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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

31 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to get a component from an object and add it to another? (Copy components at runtime) 12 Answers

How to add new instance of a script to a game object? 2 Answers

Adding an unkown script dynamically 0 Answers

Null Reference at (wrapper managed-to-native) 0 Answers

Photon Instantiate a prefab and add script on it. 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges