How to make scripts independent from each other

I want to write a script that will be independent from a framework (for instance). So, if I delete the framework, this script should run without problems:

FrameworkComponent fc = gameObject.GetComponent<FrameworkComponent>();
Debug.Log(fc.parameter);

This obviously doesn’t work if I remove the FrameworkComponent class.

Question is: how to write code in which I can safely make it work regardless of the framework existing or not?

Point is: I just wanted to debug my project for a very weird Unity error and I’m doing it through excluding code. To be able to do so, I had to go through every script depending on the code I remove. But most of them don’t really need to rely on the other classes. I would use SendMessage but that won’t easily return a value (the parameter) back in just one line or two.

Any ideas? I think this is not really possible, in csharp at least (I won’t do it in javascript or boo because languages don’t really talk very well with each other yet)… But I think it would also be quite desirable and advisable code design.

1 Answer

1

From what I understand, you want to have connected code not completely break if some components are removed. I think you want to use C# Events rather than SendMessage. But it’s definitely more lines of code than SendMessage. But events can fire and it doesn’t matter if nothing is listening to them.

Here’s a post explaining how it works: C# events and Unity3d

Here’s an example of how I did a game timer.

public class GameTimer {

public delegate void GameEventHandler();
public event GameEventHandler TimeComplete;

public void Complete() {
	Debug.Log("GameTimer >>> Complete");
	
	TimeComplete();
}

And in the Game class I listen for that event like this…

public class Game : MonoBehaviour {

private GameTimer _timer;

void Start() {
		_timer = new GameTimer(30); // timer
		_timer.Start();
		_timer.TimeComplete += TimeComplete;
}

public void TimeComplete() {
		Debug.Log( "I'm called in Game.cs when timer is done!");
	}
}

I hope that helps!