I wrote the code to generate a GameObject on start. When CreateGameObject()
is executed, RPC is executed and a GameObject is created with PhotonNetwork.Instantiate()
. Assign that GameObject to a temporary GameObject type temporaryObj
and return it.
void Start()
{
PhotonNetwork.OfflineMode = true;
string objName = "A";
GameObject obj = CreateGameObject(objName);
Debug.Log(obj); // Null
obj.SetActive(true); // ERORR
}
GameObject temporaryObj;
GameObject CreateGameObject(string objectName)
{
photonView.RPC(nameof(CreateGameObjectRPC), RPCTarget.All, objectName);
return temporaryObj;
}
[PunRPC]
void CreateGameObjectRPC(string objectName)
{
temporaryObj = PhotonNetwork.Instantiate(objectName, new Vector3(0, 0, 0), Quaternion.identity);
}
However, I get an error at obj.SetActive(true)
.
NullReferenceException: Object reference not set to an instance of an object
What else do you need to call the RPC?
It looks like you have it right, but function return values are mixed up.
The NullReferenceException is because you call CreateGameObject, and return a null temporaryObj, which was instantiated as a null object in the line above it.
Then it tries to print the null object, and set it Active.
The CreateGameObjectRPC sets the temporary object, and that is the one that should be returned.
Try something like this (untested):
void Start()
{
PhotonNetwork.OfflineMode = true;
string objName = "A";
GameObject obj = CreateGameObjectRPC(objName);
Debug.Log(obj); // Null
obj.SetActive(true); // ERORR
}
[PunRPC]
GameObject CreateGameObjectRPC(string objectName)
{
CreateGameObject(objectName);
return PhotonNetwork.Instantiate(objectName, new Vector3(0, 0, 0), Quaternion.identity);
}
void CreateGameObject(string objectName)
{
photonView.RPC(nameof(CreateGameObjectRPC), RPCTarget.All, objectName);
}
In the above, the GameObject is returned after instantiating.