• 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
Question by Dracolyte · Apr 04, 2021 at 05:43 AM · instantiatearrayclassconstructor

How can I instantiate a object with a constructor?

I created a constructor for my NPCs. I struggle with instantiating them (as a gameobject) via the constructor with its own health etc. And what can I do, to set for each instantiated Gameobject NPC the health etc? I want to somet$$anonymous$$ng like t$$anonymous$$s: Instantiate(NPC[0], NPC[0].Position, NPC[0].Rotation). I want to Instantiate a prefab with its health etc from the constructor. I cant change the properties from the array of NPC constructors in the inspector, so i need to do it by code.

NPC constructor:

  [System.Serializable]
     public class NPC : Obstacle
     {
         public bool HasPath { get; set; }
         public GameObject Path { get; set; }
         
     
         public NPC(float hp, int id, Vector3 position, Quaternion rotation,GameObject prefab, bool hasPath, GameObject path) : base(hp, id, position, rotation, prefab)
         {
             HP = hp;
             ID = id;
             Position = position;
             Rotation = rotation;
             HasPath = hasPath;
             Path = path;
             Prefab = prefab;
         }
     
         public void CreateNPC()
         {
             Instantiate(t$$anonymous$$s.Prefab, t$$anonymous$$s.Position, t$$anonymous$$s.Rotation);
         }
     }

Comment

People who like this

0 Show 0
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

4 Replies

· Add your reply
  • Sort: 
avatar image

Answer by rh_galaxy · Apr 04, 2021 at 07:56 AM

A variant of the answer above is that you can skip the extra classes and just Init the Instantiated object directly.

 //Level.cs
 public class GameLevel : MonoBehaviour
 {
     //drag your prefab with Enemy-script
     //attached to t$$anonymous$$s var in the Inspector
     public Enemy oEnemyObjBase;
 
     //List<Enemy> aEnemyList;

     void BuildLevel()
     {
         Enemy oEnemy = Instantiate(oEnemyObjBase, t$$anonymous$$s.transform);
         oEnemy.Init(10.0f);
         //aEnemyList.Add(oEnemy); //you can also save the enemy in a list for easy access
     }
     //...
 }
 
 //Enemy.cs
 public class Enemy : MonoBehaviour
 {
     float fHealth;
     
     public void Init(float health)
     {
         fHealth = health;
     }
     //....
 }
Comment
Bunny83
dbolesta

People who like this

2 Show 3 · 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 Bunny83 · Apr 04, 2021 at 03:10 PM 3
Share

Right and additionally you could aim for a chaining structure as you may know from other languages. So you can implement your Init method like this:

 public Enemy Init(float health)
 {
     fHealth = health;
     return this;
 }

That way you can simply chain the Init method after your Instantiate call in a single line which gives a more "constructor like" feeling:

 Enemy oEnemy = Instantiate(oEnemyObjBase, this.transform).Init(10.0f);
avatar image dbolesta Bunny83 · Oct 30, 2021 at 05:24 PM 0
Share

Thanks rh_galaxy and Bunny83, this is a really nice solution. What exactly is return this doing in this Init function? It's the one part where I don't quite understand why it's necessary.

avatar image Bunny83 dbolesta · Oct 30, 2021 at 10:44 PM 0
Share

As I said it allows "chaining". Usually when you call Instantiate you get back a reference to the newly created object. If you directly call a method on that instance, you can not store that instance in a variable at the same time. If the Init method is a normal method without a return type (void) the example line at the end of my comment would not work. By having the Init method returning its own instance you can chain either method calls or, as in my example, store or use the reference afterwards.

Actually the example that rh_galaxy gave is exactly this case. He first stores the reference in a variable and then calls the method on that stored reference. So if you want to store the enemy in a list like in the commented out example you need those 3 lines. When Init returns its own instance you can simply do

 aEnemyList.Add( Instantiate(oEnemyObjBase, transform).Init(10.0f) ); 

Here the return value of the Init method will actually be passed into the Add method of aEnemyList.


This is not "necessary" as you called it. The answer of rh_galaxy works fine as it is. I thought I already made it clear by introducing my comment with:

additionally you could ....

... That way you can simply chain the Init method after your Instantiate call in a single line which gives a more "constructor like" feeling

: The whole concept is known as Fluent interface.

avatar image

Answer by KoenigX3 · Apr 04, 2021 at 07:03 AM

If you have NPC objects with custom values, and you want to instantiate gameobjects with those NPC components, you could use somet$$anonymous$$ng like t$$anonymous$$s:

 GameObject go = Instantiate(t$$anonymous$$s.Prefab, t$$anonymous$$s.Position, t$$anonymous$$s.Rotation);
 go.AddComponent<NPC>().Setup(t$$anonymous$$s);


Since I cannot control the constructor, I use the Setup() method to set the values. As a parameter, I would use another NPC object, and basically copy the values from it.

 public void Setup(NPC npc)
 {
    HP = npc.HP;
    ID = npc.ID;
    //...
 }
Comment
Bunny83

People who like this

1 Show 0 · 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

Answer by amitDklein · Dec 10, 2021 at 08:58 PM

Hey, I just found t$$anonymous$$s article. It basically say that you can create a object with the variables and then instantiate it.

.

https://gamedevbeginner.com/start-vs-awake-in-unity/

Comment

People who like this

0 Show 0 · 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

Answer by slimkool · Jan 02 at 12:29 PM

you can disable script through editor and after initialisating enable again :

 GameObject CrushedSprite = Instantiate(SpritesStorage.Instance.CrushedSprites[x], V3Pos, Quaternion.identity);
 CrushedSprite.GetComponent<CrushedBehavior>().Setup(Direction, Speed);
 CrushedSprite.GetComponent<CrushedBehavior>().enabled = true;
Comment

People who like this

0 Show 0 · 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

153 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 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 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 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 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

Can't assign an instantiated class to an array? 1 Answer

How to add GameObject to List using a constructor method 1 Answer

Instantiating gameobjects in an array / class problem | NullReferenceException: 0 Answers

Need my function to work with different lists of different values (classes) 1 Answer

IndexOutOfRangeException: Array index is out of range when using an Array and instantiating 2 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