- Home /
create custom class
HI.
I want create custom class in my script and define custom variables in this class. for do this I create another public class and defined my variables inside it. but when i play the game, it give me below error:
NullReferenceException: Object reference not set to an instance of an object
This is my script:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class _Player : MonoBehaviour {
Player player;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
player.x = transform.position.x;
player.y = transform.position.y;
}
}
public class Player
{
public float x;
public float y;
}
Anyone know why unity give me this error?
Thanks.
Answer by toddisarockstar · Sep 08, 2017 at 12:17 AM
when you make a new instance of your class you have to initialize it first before you can do anything with it.
player = new Player();
Your answer

Follow this Question
Related Questions
Passing an instance of a class to different game objects 2 Answers
How to declare multiple variables using a for loop in class declaration? 0 Answers
Control which class is instantiated first 1 Answer
replacing instance of class from within itself 0 Answers
Saving class data without having lots of references? 1 Answer