How to optimize this scripts ?
Hello^, I making a multiplayer in my game by NetworkManager and Console write about this problem's:
NullReferenceException: Object reference not set to an instance of an object
FloatingPlayer2DController.Spawn () (at Assets/FloatingPlayer2DController.cs:131)
NullReferenceException: Object reference not set to an instance of an object spavni.Generate () (at Assets/spavni.cs:14)
Code from FloatingPlayer2DController (128-133 lines ) :
if (energy > 71) //128 ;
{ //129;
RaycastHit _hit; //130;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //131 ;
if (Physics.Raycast(ray, out _hit)) //132;
Instantiate(Prefabyy, new Vector3(_hit.point.x, _hit.point.y, _hit.point.z), transform.rotation); /133
And , code , from spavni script (all script's lines) :
using UnityEngine; //1
public class spavni : MonoBehaviour { public GameObject eat; public float Speed;
void Start ()
{
InvokeRepeating("Generate", 0, Speed);
}
void Generate()
{
int x = Random.Range(0, Camera.main.pixelWidth); //14
int y = Random.Range(0, Camera.main.pixelHeight);
Vector3 Target = Camera.main.ScreenToWorldPoint(new Vector3(x, y, 0));
Target.z = 0;
Instantiate(eat, Target, Quaternion.identity);
}
}
Thank you, it is realy important for game release ^
Answer by Lootheo · Feb 25, 2017 at 07:41 AM
You are probably not using the main camera of the scene (Might be deleted or Inactive) in that case the reference you are trying to make fails because there is no "Camera.main" which seems to be referenced in both cases.
You might do something like this to find the Camera in both cases, or just declare the camera as public and manually assign it.
Camera myCamera;
// Update is called once per frame
void Update () {
myCamera = FindObjectOfType<Camera>();
RaycastHit _hit; //130;
Ray ray = myCamera.ScreenPointToRay(Input.mousePosition); //131 ;
if (Physics.Raycast(ray, out _hit)) //132;
Instantiate(myPrefab, new Vector3(_hit.point.x, _hit.point.y, _hit.point.z), transform.rotation); //133
}
O, I have 2 cameras- one (not main ) on the spawn (lobby of network manager scene) and one($$anonymous$$ainCamera) is add for a Player prefab ( what is spawned from Network manager) :3
Answer by nickcooper · Feb 25, 2017 at 01:42 PM
Are you destroying your instantiated objects/prefabs at some point? If you are it would cause this error. I've been through something similar. I would suggest looking into inactivating the objects/prefabs instead of destroying them and object pooling if this is the case.
https://unity3d.com/learn/tutorials/topics/scripting/object-pooling
Yes, I can to drag and drop and instantiate object's on doubleclick in game
Your answer
Follow this Question
Related Questions
Designing a multiplayer lobby for LAN 1 Answer
What's the [command] attribute with the new Network Manager? 0 Answers
UNET Clients Laggy 0 Answers