Search Unity

Question Test missing references

Discussion in 'Testing & Automation' started by Fangh, Mar 20, 2022.

  1. Fangh

    Fangh

    Joined:
    Apr 19, 2013
    Posts:
    274
    Hello everyone,
    Let me explain the context :

    when you have a scene with a lots of monobehaviour that have a lots of references between each other, it often happens that you update a prefab or change a variable name and BOUM all the references are missing and you only see it when you play your game.

    I would like to able to check every monobehavior of a scene before building, to be sure nothing has been broken.

    as a Test, imagine you have a scene with a player, a button and and door. The button has a script called DoorOpener attached to a trigger collider that need a reference to the door to animate it.

    What I did is to load my scene then test the references. Thanks to this post : https://forum.unity.com/threads/play-mode-tests-scenehandling.751049/

    This is what I did, please tell me what you think :

    upload_2022-3-20_12-55-13.png

    upload_2022-3-20_12-55-24.png
     
    Last edited: Mar 20, 2022
  2. Fangh

    Fangh

    Joined:
    Apr 19, 2013
    Posts:
    274
    Here is another try, which did not work :
    upload_2022-3-20_14-42-25.png

    upload_2022-3-20_14-42-39.png
     
  3. Dextozz

    Dextozz

    Joined:
    Apr 8, 2018
    Posts:
    493
    I wouldn't use Unit tests for this. It's a bunch of manual work and you'll have to rerun tests every time you enter play mode. That would usually be fine, but your tests will pass 99.9% of the time, causing delays in all other tests and just waiting your time.

    Instead, I would think of maybe using MonoBehavior.OnValidate() and log an error in the console if the value is invalid or something like that.

    Or, maybe I would look into custom attributes to easily cover all fields that need some kind of a check.

    Or, at the very least, with your solution, I would declare an interface
    Code (CSharp):
    1. public interface IReferenceChecker
    2. {
    3.    bool CheckReferences();
    4. }
    and all of your classes that need their references check would implement it. You would simply return true if all references are correct, otherwise, false. With that, you would search for all gameObjects of type <IReferenceChecker> and you would have a single test to check all references of objects in the scene (hint: how are you going to handle checking references on prefabs not in the scene?) instead of having a test per object type

    It's just a bunch of ideas to nudge you in the right direction. Personally, if I was thinking of writing tests to test references in the scene, I would rethink my approach to references instead.