- Home /
Question by
batatinha380614 · Dec 10, 2021 at 02:02 AM ·
script.scripting beginner
call a method for every game object with the script attached
well... what i'm trying to do is, an way to call a method in every gameObject with the script attached
what i want to do is something like the void Update/Start/Awake:
//First Script
public class Caller
{
int newValue = 3;
public void ChangeValue()
{
//Call this method for every GameObject with the Receiver script
Receiver.ChangeValue(newValue);
}
}
//Second Script
public class Receiver
{
public int value = 1;
void ChangeValue(int value)
{
this.value = value;
}
}
Comment
Best Answer
Answer by Namey5 · Dec 10, 2021 at 08:06 AM
One way would be to use a delegate/event;
// Create a delegate type that matches your ChangeValue function
public delegate void MyDelegate (int a_Value);
public class Receiver : MonoBehaviour
{
public int value = 1;
// Create a static event out of the delegate
public static event MyDelegate ChangeValueEvent;
private void Awake ()
{
// Subscribe our ChangeValue function to the event when this object is created
ChangeValueEvent += ChangeValue;
}
private void OnDestroy ()
{
// Also unsubscribe from the event when this object is destroyed
ChangeValueEvent -= ChangeValue;
}
public void ChangeValue (int a_Value)
{
value = a_Value;
}
}
From there, you can just call the event instead of the function;
public class Caller
{
private int m_NewValue = 3;
public void ChangeValue ()
{
// You can call ChangeValueEvent like a normal function, but using the syntax below also handles cases where no Receiver objects exist (and would therefore throw a NullReferenceException)
Receiver.ChangeValueEvent?.Invoke (m_NewValue);
}
}
Your answer
Follow this Question
Related Questions
How do I make a photography function? 0 Answers
Show speed in UI 1 Answer
How to keep the old line text? 1 Answer
loop vs if spell casting script 1 Answer
how can you make a 3D model slowly become transparent? 2 Answers