Reputation: 280
I am following a tutorial series.
I have come across a problem. I understand what the error message:
Object reference not set to an instance of an object
means, but I'm not sure why this message has appeared. I'm not sure why it cannot reference it. I am quite new to Unity.
I have also created my project in documents/UnityProjects/PongTutorial
, where PongTutorial
is the name of this project.
I created a folder for my Unity projects in order to keep them together. Could there be problems creating my Unity projects in a folder called UnityProjects
instead of creating each project in the My Documents
folder?
I have created a gameManager
and attached a script to it called GameSetup
, where the code within this script is:
using UnityEngine;
using System.Collections;
public class GameSetup : MonoBehaviour
{
Camera mainCam;
BoxCollider2D topWall, bottomWall, leftWall, rightWall;
Transform player1, player2;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
topWall.size = new Vector2(mainCam.ScreenToWorldPoint(new Vector3(Screen.width * 2f, 0f, 0f)).x, 1f);
topWall.center = new Vector2(0f, mainCam.ScreenToWorldPoint(new Vector3(0f, Screen.height, 0f)).y + 0.5f);
}
}
I have cleaned, built and rebuilt Assembly-CSharp
in MonoDevelop for this script, and PongTutorial
in MonoDevelop also, where I am getting the warnings about mainCam
and all of the variables of type BoxCollider2D
.
These warnings say that they are never assigned to, so will have a null value, which is true. However, I am getting the object reference not set to an instance of an object
for the topWall.size
and topWall.center
lines.
I have just tried to create new objects. For example, in Start
I have mainCam = new Camera()
, but this doesn't seem to work. In the video, the variables are visible in the Inspector for the GM or GameManager in my case. However, this is not the case for me.
Upvotes: 1
Views: 2298
Reputation: 1324
Jan solved the issue, but I just wanted to offer an alternative in case you wanted your members to be private.
Just put the <Serialize>
decoration on the members you want to show up in the inspector.
<Serialize>
Camera mainCam;
<Serialize>
private BoxCollider2D topWall, bottomWall, leftWall, rightWall;
Upvotes: 2
Reputation: 13604
You first need to make your variables public, otherwise they will not show in the inspector:
public class GameSetup : MonoBehaviour {
public Camera mainCam;
public BoxCollider2D topWall, bottomWall, leftWall, rightWall;
public Transform player1, player2;
// rest of your code...
}
Then drag some game objects (with the proper components attached to it) into the new fields in the inspector. This should fix the 'object reference not set to an instance of an object' error message. This error message basically means that you are trying to do work on an variable which has no value set.
Upvotes: 4