Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 bakman · Mar 26, 2014 at 02:57 PM · genericc# dll

Generic method and factory pattern

Hi, I want to instantiate dynamicaly object with a generic factory pattern. The object must be inherit Enemy class. I cant pass GetType() in my generic method Thanks

public class Factory : MonoBehaviour {

     public GameObject basic;

 // Use this for initialization
 void Start () {
     
 }
 
 // Update is called once per frame
 void Update () {
 
 }

 public void Build<T>() where T : Enemy, new()
 {
     T t = new T();

     GameObject go = (GameObject)Instantiate(basic,Vector3.zero, Quaternion.identity);
     go.name = t.GetType().ToString();
     go.GetComponent<MeshRenderer>().material = Resources.Load(go.name) as Material;
     go.AddComponent<T>();

 }

}

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;

 public class Detector : MonoBehaviour {

   
     public List<Enemy> enemys = new List<Enemy>(); // content (Warrior, Paladin, Etc) 

     void OnTriggerEnter(Collider col)
     {
         if (col.tag == "Player")
         {
         
             Enemy e = enemys[Random.Range(0, 4)];
         
             GetComponent<Factory>().Build<e.GetType()>(); // Compiler doesnt want that
         

         }

    
     }
 }
 public class Mage : Enemy {


 }
 public class Warrior: Enemy {


 }
 public class Paladin: Enemy {


 }

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

3 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by Jamora · Mar 26, 2014 at 06:43 PM

You can't use generics like that. The passed type parameter must be a constant at compile time, so expressions aren't allowed.

The easiest fix would be to not use generics at all and pass the type as a parameter instead

 public void Build(System.Type type){
     if(!type.IsSubclassOf(typeof(Enemy))) return; //don't do anything if we didn't get an enemy-class
     GameObject go = (GameObject)Instantiate(basic,Vector3.zero, Quaternion.identity);
     go.name = type.ToString();
     go.GetComponent<MeshRenderer>().material = Resources.Load(go.name) as Material;
     go.AddComponent(type);
 }

If you don't want to, or unexpected complications arise in your design from sending types to the factory, you could probably use with an enum instead, since you have a limited number of classes and they are unlikely to change. Enums can be easily converted to strings and then to types( using System.Type.GetType(classname); )

An alternative would be to have a list of all accepted types in the factory. You could set it up in Awake, or use reflection to fill it.

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 moxiewhimsy · Mar 26, 2014 at 07:31 PM 0
Share

This solution is more elegant though. Disregard my suggestion.

avatar image
0

Answer by moxiewhimsy · Mar 26, 2014 at 05:13 PM

Try using

 go.AddComponent( go.name );

or more directly

 go.AddComponent( t.GetType().ToString() );

The string must be the exact name of the component type you'd like to add.

edit: Ahh. I see. IMHO, a protected enum would probably be the simplest solution.

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 bakman · Mar 26, 2014 at 06:18 PM 0
Share

Thx for your response but the problem is in OnTriggerEnter methods.

    GetComponent<Factory>().Build<e.GetType()>(); //e.GetType() prevents to compile
avatar image
0

Answer by bakman · Apr 02, 2014 at 09:12 AM

I found the solution with reflexion. Thx for responses @Jamora yes I think pass the parameters to System.Type is a good solution if we cant do with reflexion. and yes enum is pretty good way if you dont have lot of class. Bye

  int result = Random.Range(0, enemys.Count);
 
             var t = typeof(Factory);
             var e = enemys[result];
             var m = t.GetMethod("Build");
             var build = m.MakeGenericMethod(e.GetType());
             var factory = GetComponent<Factory>();
             build.Invoke(factory,null);
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

22 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

Related Questions

Generic Component Declaration 1 Answer

Animation Preview 0 Answers

Non-humanoid Rig Gets Mangled in Mecanim 0 Answers

Generic Method help 1 Answer

Inconsistent accessibility: field type 'QueueCS.QueueGridHead' is less accessible than field 'QueueCS.Form1.Rightss' and how to enter the textbox value stored in grid view 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