Monday, June 27, 2022
HomeGame Developmentunity - Find out how to reference a script that is on...

unity – Find out how to reference a script that is on only one object in the identical scene by way of code?


When you have only one object on this scene that has a TileMovement element, you could find that distinctive occasion like so:

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

That is simple to seek out within the docs, and in gobs of tutorials on-line, so you’ll want to do some fundamental looking earlier than posting right here — you may save your self a while by answering your individual questions with out having to clarify your scenario and wait for somebody to reply.


Whenever you need to do that with a element you wrote your self, one other well-liked technique is to make it a Singleton with a static occasion getter, one thing like:

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

    void Awake() {
        if (_instance != null) {
            Debug.LogWarning("Two TileMovement parts in scene, however there must be just one!");
            Destroy(this);
        } else {
            _instance = this;
        }
    }
}

Then code can simply say TileMovement.Occasion when it needs to work together with that distinctive occasion, with out incurring any search price, and with out caching its personal tileMovement variable.

You need to watch out with singletons, as a result of they’re mutable international state (bug threat) and lock you into solely ever having one (difficult to refactor in the event you later discover a want for a number of), however the identical goes for the FindObjectOfType answer, so not less than it is not including new issues in that regard.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments