0
\$\begingroup\$

I want to execute a function from many scripts attached on gameobjects which will be spawned. Since game objects are spawned, I can't assign the script in the inspector. What i want is that, there are three gameobjects, A,B,C. C is already in the scene. A and B are spawned with different scripts,the spawned gameobject's script should call the function on the gameobject C. I can make a delegate but there are different scripts that want to call the function. So should i have to create different delegates for each script on A and B and then assign them onto the gameobject C so that A and B can call their delegates and these delegates will trigger the function on C or there is something like a event that i can call from B. If it was possible, i can create a event on A and assign it on C. Now A can call the delegate and B can also call that event and trigger the function on C, but this is not possible as event can't be called from another script.

I need something like a function that i can call from any script and it calls the function from C.

Note that function should not be static. As i can call a static function from any script but it can call only static methods, which i don't want.

\$\endgroup\$
3
  • \$\begingroup\$ I would go with: When an object is spawned then C to send a delegate pointing to its method to the spawned object (or maybe an event on A/B that C subscribes to). A and B can implement a common interface, get the components trough that interface and pass the delegate. \$\endgroup\$
    – Nikaas
    Jul 27, 2020 at 6:24
  • 1
    \$\begingroup\$ Have you tried Singletons? Try this tutorial if you don't know how to implement singletons. youtube.com/watch?v=mpM0C6quQjs \$\endgroup\$
    – Swati
    Jul 27, 2020 at 7:49
  • 1
    \$\begingroup\$ I think the abstraction down to A/B/C might be making this less clear. Can you tell us what these objects are in your game, and what game feature you're implementing through these calls? With that context, we may be able to better target solutions that are appropriate for that use case, or suggest better alternatives. \$\endgroup\$
    – DMGregory
    Jul 27, 2020 at 12:15

1 Answer 1

0
\$\begingroup\$

I used an abstract class in which i put my event. Then i implemented that abstract class on A and B. Now i can call the event from both the game objects even they have different scripts.

\$\endgroup\$
1
  • \$\begingroup\$ Please consider marking this answer as accepted! \$\endgroup\$
    – Vaillancourt
    Aug 27, 2020 at 0:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .