0

Just recently started using UNET and it has been difficult, to say the least.

I'm trying execute a few lines of code to essentially have the server assign a spawned prefab (aka the Player) a camera, set it's position and parent it to said prefab. This works fine as soon as the server is hosted - camera is attached, follows the player.. great!

However, as soon as a client joins, I get an "Object reference not set to an instance of an object" error.

Client

void RpcSetCamera()
{
    if (go.gameObject == null)
    {
        Debug.Log("Unable to attach camera");
        return;
    }

    Camera.main.transform.position = go.transform.position - go.transform.forward * 8 + go.transform.up * 2;
    Camera.main.transform.LookAt(go.transform);
    Camera.main.transform.parent = go.transform;
}

Here's the function that is called for the client.

Laurel
  • 5,965
  • 14
  • 31
  • 57
Oham
  • 33
  • 3
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) ~ Different language, but explains whats going on – Caramiriel Apr 15 '18 at 10:01

2 Answers2

0

Your Camera object should be null, that can be only explanation for the object reference not set.

0

Try checking if the object is null too.

void RpcSetCamera()
{
    if (go == null || go.gameObject == null)
    {
        Debug.Log("Unable to attach camera");
        return;
    }

    Camera.main.transform.position = go.transform.position - go.transform.forward * 8 + go.transform.up * 2;
    Camera.main.transform.LookAt(go.transform);
    Camera.main.transform.parent = go.transform;
}
Sean O'Neil
  • 1,222
  • 12
  • 22
  • Hey, thanks for replying so quickly. You were right to check whether the object was null as well.. turns out that's the reason the error is popping up. Why though? Unless my logic is incorrect, all I've got is a GameObject variable (go) instantiating the prefab GO, why would it be nulling out? – Oham Apr 15 '18 at 10:10