# How to reference a script that's on just one object in the same scene via code?

private TileMovement tileMovement;


As you can see in the code above I am trying to reference a TileMovement script, where I have some getters and setters that I want to access. I have just one instance of this script, and it's sitting on another object in the same scene.

The problem is, I don't know how to get the reference to that script instance, without doing [Serialized Field] or making it public, which I 100% don't want to do.

So how would I reference it purely with code, and no use of the editor?

If you have just one object in this scene that has a TileMovement component, you can find that unique instance like so:

void Start() {
tileMovement = FindObjectOfType<TileMovement>();
}


This is easy to find in the docs, and in gobs of tutorials online, so be sure to do some basic searching before posting here — you'll save yourself some time by answering your own questions without having to explain your situation and wait for someone to answer.

When you want to do this with a component you wrote yourself, another popular method is to make it a Singleton with a static instance getter, something like:

public class TileMovement {
static TileMovement _instance;
public static TileMovement Instance => _instance;

void Awake() {
if (_instance != null) {
Debug.LogWarning("Two TileMovement components in scene, but there should be only one!");
Destroy(this);
} else {
_instance = this;
}
}
}


Then code can just say TileMovement.Instance when it wants to interact with that unique instance, without incurring any search cost, and without caching its own tileMovement variable.

You want to be careful with singletons, because they're mutable global state (bug risk) and lock you into only ever having one (tricky to refactor if you later find a need for multiple), but the same goes for the FindObjectOfType solution, so at least it's not adding new problems in that regard.

• Cheers. I should have done more research tbh, I think I just wasn't sure how to formulate the question for Google to find the answer. A bit of noobie, not that patient. Need to learn patience if I want to get into coding. :) Jun 27 at 1:06