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 /
avatar image
1
Question by deathbane · Mar 23, 2015 at 08:17 PM · c#instantiatefunctioninstancemessage

How can I call a function in all instances of a script

I have a script that instantiates objects. I want to be able to send information to all of these objects, every time the player uses an ability. There is a maximum of 100 objects. What is the most efficient way to do this?

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 raja-bala · Mar 25, 2015 at 06:17 AM 0
Share

If all of these objects share a commons script (say Enemy.cs), then using the message passing system isn't the best way to do this.

You'd rather have the logic within Enemy.cs, wherein you check for Player.ability (lets say this is a singleton that doesn't inherit from $$anonymous$$onobehavior) in Update

3 Replies

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by sprawww · Mar 23, 2015 at 08:45 PM

Since you are instantiating the objects yourself, you can use the same class to keep track of all the created objects. What exactly it is that you use to keep track of the objects is up to you. Personally, I like List. Once you have that, you can just loop through it to send the information to all the objects.

 using System.Collections.Generic;
 
 List<GameObject> goList = new List<GameObject>();
 
 void InstantiateAddList()
 {
     GameObject go = Instantiate(//...);
     goList.Add(go);
 }
 
 void OnAbilityUse()
 {
     //Ability use stuff
     
     foreach(GameObject go in goList)
     {
         go.SendInformation();
     }
 }
Comment
Add comment · Show 13 · 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 deathbane · Mar 24, 2015 at 03:35 PM 0
Share

Okay I have this code.

 GameObject obj = Instantiate(projectile,new Vector3((x - 4) * 0.6F,5,-9),Quaternion.identity) as GameObject;
                         orbs.Add(obj.GetComponent(typeof(orb)));


That gives an error saying: "NullReferenceException: Object reference not set to an instance of an object Deck+c__Iterator1.$$anonymous$$oveNext () (at Assets/Scripts/Deck.cs:160) UnityEngine.$$anonymous$$onoBehaviour:StartCoroutine(String) Deck:save() (at Assets/Scripts/Deck.cs:79) UnityEngine.EventSystems.EventSystem:Update() ."

avatar image sprawww · Mar 24, 2015 at 03:48 PM 0
Share

Does the code work fine without the new

 orbs.Add(obj.GetComponent(typeof(orb)));

? Please remove or comment that line to make sure it is the one throwing the error.

Afterwards, you might want to replace that with

 orbs.Add(obj.GetComponent<orb>());

we can go from there if the error still exists

avatar image deathbane · Mar 24, 2015 at 04:44 PM 0
Share

It gives the error as the code executes. So no the code needs the line to work properly.

Edit: Actually yes the code works fine without it.

avatar image sprawww · Mar 24, 2015 at 04:54 PM 0
Share

I don't see any error in it, there could be something further up. Can you remove or comment the .Add line and add these ins$$anonymous$$d

 Debug.Log("1: " + orbs);
 Debug.Log("2: " + obj);

Then tell me the output Unity gives you. Least you'll know which of the 2 is causing the problem.

avatar image deathbane · Mar 24, 2015 at 05:07 PM 0
Share

It appears that obj is giving the error. Could it be something to do with Instantiate being casted as a GameObject?

Show more comments
avatar image
3

Answer by Cherno · Mar 23, 2015 at 08:49 PM

sprawww is right, but I'm gonna directly answer the original question anyway. It's definitely NOT efficient, though. Keeping track of all gameobjects/scripts manually is the best way I figure.

 YourScriptName[] yourScriptArray = FindObjectsOfType(typeof(YourScriptName)) as YourScriptName[];
         foreach (YourScriptName yourScriptName in yourScriptArray ) {
             yourScriptName .FunctionName();
         }
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 Huacanacha · Mar 23, 2015 at 09:00 PM 0
Share

And if you also need to find the inactive objects:

 Resources.FindObjectsOfTypeAll<YourScriptName>()

This will likely be even slower than FindObjectsOfType.

avatar image Colin_Peters · Aug 19, 2020 at 09:35 PM 0
Share

Thank you!!! I've been trying to get my script to work all day, and this solved my problem. Awesome!!

avatar image
1

Answer by DiegoSLTS · Mar 23, 2015 at 08:55 PM

If you can make all the instantiated objects childs of the same game object you can use the BroadcastMessage function: https://docs.unity3d.com/ScriptReference/Component.BroadcastMessage.html

It will call the function with the name you want in every component that has that function, for the game object that has the script calling the function and all it's children. I haven't tested it, but I guess it goes through the full hierarchy of childs, not just the first level.

I don't know if this is efficient, probably it takes more time than having a list of objects to call that function, but maybe you can trade a little speed at runtime for more speed at coding.

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

25 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

Related Questions

`UnityEngine.Camera.main' cannot be accessed with an instance reference, qualify it with a type name instead 2 Answers

Distribute terrain in zones 3 Answers

Multiple Cars not working 1 Answer

Instantiating on Input 1 Answer

Why does this prefab trigger all instances to action? C# 1 Answer


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