I’m not sure how to do this, but I have two scripts, [Script A] and [Script B]. Script B is dependent on Script A to function but not vice versa as Script B simply adds more functionality to the object.
If Script A has a public function that is called within Script A, how can I use Script B to basically receive calls from Script A’s function call, so that Script B can make further changes to the object when the function from Script A is called?
By the way, to reiterate, Script A is NOT dependent on Script B to function and I have to keep it that way so I cannot call a separate function in Script B from Script A…
I’d just like to know if it’s possible, and if so how I would execute this.
One way to achieve that is via events. ScriptA implements an event and invokes it when necessary, ScriptB adds a listener to the event.
public class ScriptA : MonoBehaviour
{
public event Action SomethingHappened = delegate {};
public void DoSomething()
{
// do stuff
SomethingHappened();
}
}
public class ScriptB : MonoBehaviour
{
void Awake()
{
base.GetComponent<ScriptA>().SomethingHappened += onSomethingHappened;
}
private void onSomethingHappened()
{
// do more
}
}
Note: There are more ways to implement events (just google e.g. “unity c# events”), this is just one of them. If you want to assign the listeners in the editor, you should check UnityEvents.
1 Like
Another option is inheritance, depending on the specific implementation:
public class ScriptA : MonoBehaviour
{
protected virtual void DoSomething()
{
// Does something
...
}
}
public class ScriptB : ScriptA
{
public override void DoSomething()
{
base.DoSomething();
// Does something more.
...
}
public void DoSomethingElse()
{
base.DoSomething();
// Does something else
....
}
}
1 Like
Thanks, answers were very insightful, I think Events would be better suited to my needs ![]()