Unity can't insert an object in the object script field

I have a prefab on which the script hangs. The script has a field for the public GameObject scene; the scene itself has a Scene_management object. as soon as I throw the prefab on the main stage and insert it into the script in the inspector, it is inserted. I save the modified prefab.and I remove it from the stage. But when I re-throw the prefab on the stage. there is nothing in the GameObject scene field. the script hangs on a few more prefabs, but even if I throw all the prefabs on the main stage containing this script and at the same time I insert there and all prefabs I save that too result. Help a novice programmer.

 1

1 answers

This is a feature of Unity, if you like. "Prefab" is an object template, when you throw an object on the stage - you create an instance of this prefab.

Objects on the scene exist only within the scene, but the "prefab" exists within the file system, only its instances exist within the scene. Links from the file system to the scene are not possible because the scene is not permanent.

As a result, you can assign an object from the scene to the created instance, but you can't assign it to the "prefab template" itself.

If your prefab scripts need access to the script on the stage, you can use the Singleton pattern adapted for Unity (over time, you will find better solutions, but for starters and ease of understanding, this will do):

//Класс с вашего Scene_management
public class SceneManager : MonoBehaviour
{
    public static SceneManager Instance { get; private set; }

    private void Awake()
    {
        Instance = this;   
    }

    public void DuHast()
    {
        print("Du hast mich");
    }
}

//Класс с вашего префаба
public class PrefabClass : MonoBehaviour
{
    //Следите, чтобы обращение не происходило раньше Awake
    void Method()
    {
        SceneManager.Instance.DuHast();
    }
}

In other words, in Awake, the SceneManager translates a static reference to itself, and from that point on, any other class in the game can access it through this static reference. You need to make sure that the requests did not occur before Awake. A simple rule can help with this - in Awake, the class works only with its own fields, in Start, it calls for data outside.

 3
Author: M. Green, 2020-02-20 06:38:06