Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 /
avatar image
1
Question by camander321 · Jul 06, 2016 at 12:33 AM · instantiategeneric

Instantiating GameObject from Generic Class

I am in the process of implementing a resource pool so I can reuse my objects rather than creating/destroying them constantly. I would like it to work with unity GameObjects and also any other type. This is the gist of what I have so far:

 public class ResourcePool <T> {
     
         // initializes the pool with a number of items
         public void Init(int startingSize) {}
 
         //  removes and returns unused item from pool
         public T GetItem() {}
 
         // puts item back into pool
         public void ReturnItem(T item) {}
 
         // Deletes excess unused items in pool
         public void Trim() {}
 
         // creates and adds a number of new items to pool
         private void addItems(int num)  {}
 
         // removes and deletes a number of items from pool
         private void removeItems(int num) {}
 }

My problem Is that I don't see an easy way to customize Instantiation or Deletion of objects in the pool. Obviously with most objects, a simple "new T()" would work fine. But when T is a MonoBehavior on a GameObject, or its constructor takes arguments, it gets trickier.

The only way to do it that I have come up with so far is to create child classes for each resource pool type in order to override the "addItems" and "removeItems" functions. It works, but at that point, why use generics?

How can I do this? Am I overcomplicating this or overlooking something simple? Any Ideas would be great.

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 Bunny83 · Jul 06, 2016 at 01:24 AM

The usual way when creating such a generic class is to provide a creation callback event. By default the pool would simply use "new". If you provide a callback it simply calls that callback to create a new instance. How that is done is up to the pool user.

 public event Func<T> OnCreateRequest;
 
 private T CreateInstance()
 {
     if (OnCreateRequest != null)
         return OnCreateRequest();
     var t = typeof(T);
     if (typeof(Component).IsAssignableFrom(t))
         return (new GameObject(t.Name)).AddComponent<T>();
     return System.Activator.CreateInstance<T>();
 }

This will use the "OnCreateRequest" callback if you provide one. If no callback is provided and the type is a Component it creates a new gameobject and attaches that component. If it's not a component derived type it simply uses the default constructor by using the Activator.

If the pool should pool a prefab you would simply do:

 pool.OnCreateRequest += ()=>(YourPoolType)Instantiate(yourPrefab);

So everytime the pool calls "CreateInstance" internally it will actually call

 (YourPoolType)Instantiate(yourPrefab)

If you have a "normal" class with a constructor that requires parameters you can do the same:

 pool.OnCreateRequest += ()=> new YourPoolType(42,"some other parameter");
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.

Follow this Question

Answers Answers and Comments

52 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

Related Questions

Object.Instantiate. , really? 4 Answers

Get method in script with Generic list 1 Answer

Checking if object intersects? 1 Answer

Instantiated Object being auto-deleted 0 Answers

Instantiated Bullet Force not being applied 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