1
votes

I have created a simple prefab in Unity3D. I want to add a reference to the camera, so I created a public variable m_Camera:

public Camera m_Camera;

Then I dragged the prefab into the scene, and dragged the Camera onto the UI to set the Camera I want to reference to. And finally I click "Apply" to apply the changes to the prefab.

When I run the scene, the prefab I dragged into the scene has the Camera reference, but the prefabs I instantiate at run time, have "None (Camera)" in the variable UI.

How can I set the camera reference on the prefab and save the prefab with the reference for use when Instantiating the prefab?

TIA

EDIT I have tried m_Camera = Camera.main; and m_Camera = GameObject.Find("ARCamera").camera; But both don't seem to work. I am try to get a ray cast when there is a mousedown on the prefab:

public Camera m_Camera;

    void OnMouseDown () {
        RaycastHit hitInfo;
        m_Camera = Camera.main;
        if (Physics.Raycast(m_Camera.ScreenPointToRay(Input.mousePosition), out hitInfo))
        {
            Debug.Log("Prefab was pressed");

        }
    }

We I drag the camera into the m_Camera variable via the UI at runtime in the Unity Editor it does work and I get the output to the console.

1
I don't understand what you mean by "assigning camera reference to m_Camera for prefab". I tried referencing the camera directly in the code by with no success, I tried a lot of different ways like finding the gameobject and getting the component. Do you maybe have an example of how I would accomplish this? TIA! - Ronny vdb
Is the camera part of the prefab? - rutter
@rutter no the camera is not part of the prefab - Ronny vdb
There's your problem, then. Prefabs only serialize object references within the prefab. You can set an external reference in the scene, but Unity saves that as a value override on that particular prefab instance, not a default value for the prefab. You'll need to reference an object within the prefab, or build so that the reference can be found at runtime (such as reading Camera.main during Start()). - rutter

1 Answers

1
votes

Because you can instantiate prefab from any scene and in that case prefab will not know about the camera from previous scene. In short prefab have access to global objects or there childs. Solution:

set the m_Camera in start/onenable function, something like

m_Camera = Camera.main;