• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by phili2709 · Apr 15, 2020 at 11:06 AM · objectnullreferenceexception

Instantiating Custom Object in Unity MonoBehaviour Scripts

I'm trying to programm my own little game in Unity, I'm not new to programming but new to Unity and C#. The problem is that I wrote my own classes to handle the game map and I am trying to connect these classes to the MonoBehaviour Scripts in Unity.


I have a script called InputManager, which is supposed to handle the input via mouse and keyboard etc. and in this script I want to create an object of the class MapManager which has access to my tiles and stuff. The problem I'm getting is that I can't seem to create an instance of MapManager in InputManager, not with the common new MapManager() anyway. When I use this a NullPointer of some sort is created, I guess?


I do not get a compiling error but an error once the game is launched which is:


 NullReferenceException: Object reference not set to an instance of an object
 InputManager.Update () (at Assets/Scripts/InputManager.cs:55) 
 


Thank you for your help!



!UPDATE!:


I tried using a workaround so that it does not matter if Start() or Update() is called first, meaning that I just instantiate MapManager in the first Update() call. However, when I run the program the error is still the same. My conclusion is that somehow my constructor is not working or the Monobehaviour script somehow does not allow using the standard constructor... Any ideas?


Here is my code:


InputManager.cs

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.Tilemaps;
 
 public class InputManager : MonoBehaviour
 {
     public int mapRightBorder = 10;
     public int mapLeftBorder = -10;
     public int mapTopBorder = 8;
     public int mapBottomBorder = -4;
 
     public double camSpeed = 0.2;
     public double mouseSensitivity = 0.3;
     public double scrollSensitivity = 2;
 
     public double maxZoomIn = -3;
     public double maxZoomOut = -12;
 
     public Tilemap ground, overlays, buildings;
 
     public Tilemap selected;
 
     public AnimatedTile animatedTile;
 
     private double detectionBorder;
     private double leftRightCorrection;
 
     private MapManager mapManager;
 
     // Start is called before the first frame update
     void Start()
     {
         detectionBorder = 50;
         leftRightCorrection = 1.2;
 
         mapManager = new MapManager();
 
         mapManager.ground = ground;
         mapManager.overlays = overlays;
         mapManager.buildings = buildings;
 
         mapManager.selected = selected;
 
         mapManager.animatedTile = animatedTile;
 
         Cursor.lockState = CursorLockMode.Confined;
     }
 
     // Update is called once per frame
     void Update()
     {
         moveCam();
         checkMouse();
         mapManager.updateTilemaps();
     }
 
     private void moveCam()
     {
         double moveX = Camera.main.transform.position.x;
         double moveY = Camera.main.transform.position.y;
         double moveZ = Camera.main.transform.position.z;
         
         double xPos = Input.mousePosition.x;
         double yPos = Input.mousePosition.y;
         double zDelta = Input.GetAxis("Mouse ScrollWheel");
 
         if (Input.GetKey(KeyCode.LeftArrow))
         {
             moveX -= camSpeed * leftRightCorrection;
         }
         else if (xPos >= 0 && xPos < detectionBorder)
         {
             moveX -= camSpeed * mouseSensitivity * leftRightCorrection;
         }
         else if (Input.GetKey(KeyCode.RightArrow))
         {
             moveX += camSpeed * leftRightCorrection;
         }
         else if (xPos <= Screen.width && xPos > Screen.width - detectionBorder)
         {
             moveX += camSpeed * mouseSensitivity * leftRightCorrection;
         }
 
         if(moveX > mapRightBorder || moveX < mapLeftBorder)
         {
             moveX = Camera.main.transform.position.x;
         }
 
 
         if (Input.GetKey(KeyCode.DownArrow))
         {
             moveY -= camSpeed;
         }
         else if (yPos >= 0 && yPos < detectionBorder)
         {
             moveY -= camSpeed * mouseSensitivity;
         }
         else if (Input.GetKey(KeyCode.UpArrow))
         {
             moveY += camSpeed;
         }
         else if (yPos <= Screen.height && yPos > Screen.height - detectionBorder)
         {
             moveY += camSpeed * mouseSensitivity;
         }
 
         if(moveY > mapTopBorder || moveY < mapBottomBorder)
         {
             moveY = Camera.main.transform.position.y;
         }
 
 
         if (!(moveZ + zDelta * scrollSensitivity > maxZoomIn || moveZ + zDelta * scrollSensitivity < maxZoomOut))
         {
             moveZ += zDelta * scrollSensitivity;
         }
 
         Vector3 newPos = new Vector3((float)moveX, (float)moveY, (float) moveZ);
         Camera.main.transform.position = newPos;
     }
 
     private void checkMouse()
     {
         if (Input.GetMouseButtonDown(0))
         {
             mapManager.selectTile(Input.mousePosition);
         }
     }
 }
 

MapManager.cs


 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.Tilemaps;
 
 public class MapManager
 {
     public int mapWidth = 16;
     public int mapHeight = 16;
 
     public Tilemap ground, overlays, buildings;
 
     public Tilemap selected;
 
     public AnimatedTile animatedTile;
 
     private Vector3Int currentlySelected;
 
     private OwnTilemap tilemap;
 
     public MapManager()
     {   
         tilemap = new OwnTilemap(mapWidth, mapHeight, ground, overlays, buildings);
         currentlySelected = new Vector3Int(-1, -1, 0);
     }
 
     private Vector3Int mouseToTilemap(Vector3 mousePosition)
     {
         Ray ray = Camera.main.ScreenPointToRay(mousePosition);
         // create a plane at 0,0,0 whose normal points to +Y:
         Plane hPlane = new Plane(Vector3.forward, Vector3.zero);
         // Plane.Raycast stores the distance from ray.origin to the hit point in this variable:
 
         float enter = 0.0f;
         if (hPlane.Raycast(ray, out enter))
         {
             //Get the point that is clicked
             Vector3 hitPoint = ray.GetPoint(enter);
             Vector3Int cell = ground.WorldToCell(hitPoint);
 
             return cell;
         }
 
         return new Vector3Int(-1, -1, 0);
     }
 
     private bool isInBorders(Vector3Int p)
     {
         if (p.z != 0) return false;
         if (p.x < 0 || p.x >= mapWidth) return false;
         if (p.y < 0 || p.y >= mapHeight) return false;
         return true;
     }
 
     public void updateTilemaps()
     {
         tilemap.updateTilemaps();
     }
 
     public void previewBuilding()
     {
 
     }
 
     public void selectTile(Vector3 mousePosition)
     {
         if(currentlySelected != new Vector3Int(-1, -1, 0))
         {
             selected.SetTile(currentlySelected, null);
         }
         if (isInBorders(mouseToTilemap(mousePosition)))
         {
             selected.SetTile(mouseToTilemap(mousePosition), animatedTile);
             currentlySelected = mouseToTilemap(mousePosition);
         }
     }
 }
 

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Namey5 · Apr 17, 2020 at 04:07 AM 0
Share

As much as it looks as though the null reference is pointing to the map$$anonymous$$anager object, I would actually imagine the map$$anonymous$$anager's tilemap is the object that is throwing the error. How is 'OwnTilemap' defined? Your guess for $$anonymous$$onoBehaviour constructors is almost correct - you can still call the constructor on regular objects from within a $$anonymous$$onoBehaviour, but anything that inherits from Unity's Component class (including Behaviour and $$anonymous$$onoBehaviour) cannot be constructed directly, ins$$anonymous$$d they have to exist somewhere in the scene attached to a GameObject. I will also note that in your constructor, you are passing 'ground', 'overlays' and 'buildings' to the tilemap - none of which are actually passed or declared anywhere.

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

135 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Object Inheritance NullReferenceException: Object reference not set to an instance of an object 1 Answer

Stealth Tutorial: NullReferenceException with AlarmLight 0 Answers

" NullReferenceException: Object reference not set to an instance of an object" 3 Answers

Unity Object Array C# 2 Answers

NullReferenceException help 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges