Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • 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 /
  • Help Room /
avatar image
17
Question by Phil · Nov 01, 2010 at 05:17 PM · instantiateclass

Using constructors in Unity (C#)

I would find it very useful to initialize values in constructors for many of my classes, but I just read in the scripting reference the following :

"Never initialize any values in the constructor. Instead use Awake or Start for this purpose. Unity automatically invokes the constructor even when in edit mode. This usually happens directly after compilation of a script, because the constructor needs to be invoked in order to retrieve default values of a script. Not only will the constructor be called at unforeseen times, it might also be called for prefabs or inactive game objects.

Using the constructor when the class inherits from MonoBehaviour, will make the constructor to be called at unwanted times and in many cases might cause Unity to crash. Only use constructors if you are inheriting from ScriptableObject."

Is it really so dangerous or can I use them anyway? For example, I want to instantiate various weapons in my game and give them random stats (damage, range, etc...) using a constructor that initializes these values. Would this cause problems? Or how would I use this "ScriptableObject" they mentioned? Can scripts inheriting from ScriptableObject be attached to gameObjects?

Comment
Add comment · Show 1
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
avatar image MisterBinny · Aug 28, 2016 at 12:23 AM 0
Share

So how are you supposed to instantiate the class by passing values to it? (Nobody mentions this..unbelievable.)

7 Replies

· Add your reply
  • Sort: 
avatar image
19

Answer by Daniel-Brauer · Nov 01, 2010 at 06:15 PM

As the documentation says, you shouldn't implement (and definitely shouldn't call) constructors for MonoBehaviours. One of the reasons for this is that in the best-case scenario, your constructor will be called when the game starts, and then the contents of the instance will be over-written by de-serialized data as Unity loads up your scene file.

If you want initialization code to run when the game starts, use Start() or Awake(). Awake() will be called immediately as part of the instantiation process. Start() will be called before the first Update() call that the newly instantiated object gets.

ScriptableObjects are non-Behaviour Objects that Unity lets you serialize as stand-alone assets. They're for storing data that doesn't belong to a specific level or prefab. GUISkins are a good example of a ScriptableObject.

Comment
Add comment · Show 2 · 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
avatar image xeophin · Nov 02, 2010 at 08:49 AM 0
Share

Oh, I didn't know that about ScriptableObjects. Good to know, thanks!

avatar image Ash-Blue · Feb 21, 2016 at 11:47 AM 0
Share

A good alternative is to create a public virtual Setup() method that can be inherited across your classes and called immediately after being created.

avatar image
4

Answer by Ferb · Nov 15, 2014 at 05:25 PM

For what it's worth, I've done this before. I was new to Unity but experienced in C#, so I naturally tended to do things that way. The only problem I had was that any Unity-specific code, like accessing the Transform for instance, wouldn't work in the constructor, assumably because Unity hadn't initialised those things at that stage. But if the code was just initialising basic variables or just using .NET libraries, I never had any problems with it. I think the dangers are probably overstated, but I avoid it now anyway, just because you can't call the constructors you make, which limits their usefulness (because the constructors can't have any arguments, and can't be overloaded). You can make a public initialise function and call it on the Monobehaviour derived object just after initialising it, which effectively does the same thing and avoids any harm and allows you to control the calling of it.

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
avatar image
2

Answer by xeophin · Nov 01, 2010 at 05:23 PM

You can easily use the Start() method to initialise and randomise the values of your weapons it is automatically called when an object becomes part of a scene, and it should make no difference for you (apart from the fact that, yes, technically, Start() is not the constructor ;) ).

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
avatar image
1

Answer by Mike 3 · Nov 01, 2010 at 05:25 PM

If you instantiate a monobehaviour via the constructor, things would go pretty bad fast - it'll be only the c# side of the component, and won't be attached to an object

Adding the constructor itself is usually a bad idea too - it'll load the code at random times

Instead, think about adding an Init method with all the parameters you'd use in the constructor

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
avatar image
1

Answer by Tumbo The Gnome · Mar 03, 2015 at 12:20 AM

One pattern that I've been experimenting with lately to aid with inheritance involves using the constructor to subscribe to event/delegates defined in the base class. For example:

 public class Example : MonoBehaviour
 {
     public delegate void ExampleAction();
 
     protected ExampleAction awakeAction;
     protected ExampleAction startAction;
     protected ExampleAction updateAction;
     protected ExampleAction customEvent;
 
 
     private void Awake()
     {
         if(this.awakeAction != null)
         {
             this.awakeAction();
         }
     }
 
     private void Start()
     {
         if(this.startAction != null)
         {
             this.startAction();
         }
     }
 
     private void Update()
     {
         if(this.updateAction != null)
         {
             this.updateAction();
         }
     }
 
     public void CustomEvent()
     {
         if(this.customEvent != null)
         {
             this.customEvent();
         }
     }
 }
 
 public class Test : Example
 {
     public Test()
     {
         this.awakeAction += () =>
         {
             Debug.Log("Awake");
         };
     }
 }

 
Comment
Add comment · Show 1 · 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
avatar image TheTechn0mancer · Feb 24 at 06:14 PM 0
Share
 public class Example : MonoBehaviour
  {
      public delegate void ExampleAction();
  
      protected ExampleAction awakeAction = delegate { };
      protected ExampleAction startAction = delegate { };
      protected ExampleAction updateAction = delegate { };
      protected ExampleAction customEvent = delegate { };
 
      private void Awake() => this.awakeAction();
      private void Start() => this.startAction();
      private void Update() => this.updateAction();
      public void CustomEvent() =>  this.customEvent();
  }
  
  public class Test : Example
  {
      public Test()
      {
          this.awakeAction += () => Debug.Log("Awake");
      }
  }

  • 1
  • 2
  • ›

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.

Follow this Question

Answers Answers and Comments

7 People are following this question.

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

Related Questions

Changing an argument to a var and vice-versa 0 Answers

Instantiating 2 separate sprites as one? 1 Answer

Unity3d 4.6 javascript prefab with script 1 Answer

Problem with custom bolts in Space Shooter 1 Answer

How can I change this script so that each instantiated prefab spawns a set amount faster 0 Answers


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