- Home /
Using script's method from all of the gameobjects that has that script
The name pretty much says it all. I need to run one method from a script in all gameobjects that have that script in them(if this changes anything: I need to make this work from an RPC). How could I do that?
P.s. C# only please
Answer by plainerman · Oct 11, 2014 at 07:01 PM
There are several ways to do this! In my opinion the most beautiful way to do this would be to make a manager. Make a script called MyScriptManager.cs
using UnityEngine;
using System.Collections;
public class MyScriptManager: MonoBehaviour
{
public static List<MonoBehaviour> myScripts = new List<MonoBehaviour>();
public static void AddNewEntry(MonoBehaviour mono)
{
if(mono!=null)
list.add(mono);
}
...
}
You may have to add using System.Collections.Generic;
Afterwards you can add to your Script:
using UnityEngine;
using System.Collections;
public class MyScript: MonoBehaviour
{
...
void Awake()
{
MyScriptManager.AddNewEntry(this);
}
}
And whenever you want to call the function on all Scripts use this in your MyScript class:
void Update()
{
if(something)
{
foreach(MonoBehaviour mono in MyScriptManager.myScripts)
{
((MyScript)mono).callAwesomeFunction();
}
}
}
You may can't copy + paste because I wrote it without compiler! Hope this solves your problem!
Thanks for answering! I thought that there might be an easier way to do this, but looks like not :/
Answer by Vsenik · Oct 11, 2014 at 07:00 PM
There are several scenarios. It is unclear about what you really wanna do. But if I undestand you correctly then you could use script made by Cerebrate
Simple example of usage:
public interface ICanDoSomeAction
{
void SomeAction();
}
class Digger : MonoBehaviour,ICanDoSomeAction
{
public void SomeAction()
{
Dig();
}
private void Dig()
{
Debug.Log(gameObject.name + " digs");
}
}
class Archer : MonoBehaviour,ICanDoSomeAction
{
public void SomeAction()
{
Shoot();
}
private void Shoot()
{
Debug.Log(gameObject.name + " make a shot");
}
}
class Manager:MonoBehaviour
{
public GameObject[] Actors;
private ICanDoSomeAction[] actions;
public
void Start()
{
actions = new ICanDoSomeAction[Actors.Length];
for (int i = 0; i < Actors.Length; i++)
{
actions [i] = Actors [i].GetInterface<ICanDoSomeAction>();
}
}
void Update()
{
foreach (var a in actions)
a.SomeAction();
}
}
Thank you! Yours and playerman's answers are great, sorry that I did not chose yours as the correct one, but I had to choose...
Your answer
Follow this Question
Related Questions
Camera to follow a target within a circle? 1 Answer
Assigning current color to a variable for fade out (C#) 0 Answers
C# Gameobject's Script's ValuesEquals Other Gameobject's script's Values 1 Answer
NullReference when accessing GameObject in array (C#) 1 Answer
Getting nullreference error while using sendmessage 1 Answer