Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
2 captures
12 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 /
avatar image
0
Question by rrkpp · Apr 22, 2016 at 05:26 AM · scripting problemruntime

Add all scripts in a folder to a GameObject at runtime?

Hi all,

I have a Resource folder which contains some scripts. I want to, from another script's Start() function, loop through all the scripts in a specific folder and add each one of those scripts to a GameObject as a new component. How can I accomplish this?

I'm able to get each script as an Object via Resources.LoadAll(), and from there I can get the name of the script as a string, but not a type. Type.GetType(scriptName) doesn't work because it requires the assembly name, AddComponent(scriptName) is deprecated since Unity 5 and Resources.LoadAll() returns an array of Objects and I can't cast them to the appropriate script types to be added to the GameObject.

If anyone has any ideas I'd really appreciate the input! Thanks

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 OrnelasOne · Feb 06, 2018 at 08:22 PM 0
Share

Did you solve it?

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by ShadyProductions · Feb 06, 2018 at 09:36 PM

To answer the main question, and @OrnelasOne's question and for any other people who might be looking for the answer.. I figured out how to do it:

 using UnityEditor;
 using UnityEngine;
 
 public class ScriptLoader : MonoBehaviour {
 
     void Start () {
         // Cast to MonoScript object
         var scripts = Resources.LoadAll<MonoScript>("Scripts");

         var go = new GameObject("blabla");
         foreach (var script in scripts)
         {
             // GetClass method returns the type of the script
             go.AddComponent(script.GetClass());
         }
     }
 }

https://docs.unity3d.com/ScriptReference/MonoScript.html

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
0

Answer by Kestu · 2 days ago

I found another way to do it. This way you dont have to attach it as a script to a gameobject. It does require you attach a specific interface to all scripts you want to run. It also fetches scripts from the entire project and not just in a single folder.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using System.Reflection;
 using System;
 using System.Linq;
 
 public class GetAllScriptsExample : MonoBehaviour
 {
     //attach this script to a gameobject somewhere so the awake can run
     //it gets every single script in the project with "IItemInterface" on it and runs "GetItem();" on all of them.
     //This loads scr_Item objects into a static dictionary. You could make it do anything though.
 
     public static IDictionary<string, scr_Item> itemDict { get; private set; } = new Dictionary<string, scr_Item>();
 
     void Awake()
     {
         Assembly assembly = Assembly.GetAssembly(typeof(IItemInterface));
         var allItems = assembly.GetTypes()
             .Where(t => typeof(IItemInterface).IsAssignableFrom(t) && t.IsAbstract == false);
 
         foreach (System.Type script in allItems)
         {
             IItemInterface myRecipeInterface = Activator.CreateInstance(script) as IItemInterface;
             scr_Item item = myRecipeInterface.GetItem();
 
 
             if (itemDict.ContainsKey(item.name))
             {
                 //do nothing
                 Debug.Log("item problem detected: duplicate item " + item.name);
             }
             else
             {
                 itemDict.Add(item.name, item);
             }
         }
     }
 
 }
 

Then here is an example of an scr_Item that this script can fetch. Notice the IItemInterface on there.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class scr_DistilledWaterItem : IItemInterface
 {
     public scr_Item GetItem()
     {
         scr_Item thisItem = new scr_Item();
 
         thisItem.name = "Distilled Water";
         thisItem.description = "Water with all mineral impurities removed. An even stronger solvent.";
         thisItem.maxStackSize = 100;
         thisItem.color = new Color32(255, 255, 225, 255);
         thisItem.intensity = 0;
 
         Sprite distilledWaterSprite = Resources.Load<Sprite>("Sprites/Icons/Fluids/distilledWater");
         thisItem.sprite = distilledWaterSprite;
 
         return thisItem;
     }
 }
 

And then finally the interface itself:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public interface IItemInterface
 {
     /// <summary>
     /// Use this to build items at runtime.
     /// </summary>
     scr_Item GetItem();
 }


I got this code from this video: https://youtu.be/nqAHJmpWLBg

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

6 People are following this question.

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

Related Questions

Server side c# scripts loads at runtime 0 Answers

Texture.GetNativeTexturePtr sometime returns 0. 2 Answers

Runtime mesh decimation 1 Answer

Export objects to a .3DS file at runtime 1 Answer

Put a prefab in Hierarchy without using Instantiate ? (from code) 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