- Home /
Question by
rev3rse · Jan 19, 2014 at 11:03 PM ·
c#dependency injection
How to share an object to other scripts
I'm trying to inject(DI) an object to a bunch of other scripts without doing statically, is there a way to do that?
For example:
public class InitGame : MonoBehaviour {
void Start() {
TileMape tileMap = ...
}
}
public class AnotherScript : MonoBehaviour {
public TileMap tileMap;
void AnotherScript (TileMap injectedTileMap): base() {
tileMap = injectedTileMap;
tileMap.DoStuff();
}
}
How can I do something like this without making the TileMap instance static or using the singleton design pattern?
Comment
Best Answer
Answer by Benoit Dufresne · Jan 20, 2014 at 12:38 AM
Just put that script on an empty gameobject, then in the other scripts' Start function, use FindObjectOfType to reference it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613130906im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
[C#]Angle of shooting equale to mouse direction 1 Answer
Character getting stuck on curbs.. 0 Answers