472,371 Members | 1,651 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,371 software developers and data experts.

Unity2D, can't print a public field on the screen

I am doing a 2D platformer using Unity, there is an object that moves by a script (the character). There are diamonds that are put on the level scene, they can be collected by the character. The character's class has a public field that saves the amount of collected diamonds . It's starting value is zero. I managed to make it so that when touching a diamond, this variable increases by 1, and the diamond is destroyed. But I can't display the value of this field on the screen. I tried it like this: I created a canvas, put the text on it, hung the following script on the text:
Expand|Select|Wrap|Line Numbers
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5.  
  6. public class textScr : MonoBehaviour { 
  7.     private MovingObj _movingObj;
  8.     private Text _diamondText;
  9.  
  10.     void Start()
  11.     {
  12.         _movingObj = GameObject.Find("Square").GetComponent<MovingObj>();
  13.     }
  14.  
  15.     public void Update()
  16.     {
  17.         _diamondText.text = "Diamonds: " + _movingObj.diamondsQuantity.ToString();
  18.     }
  19.  
  20. }
  21.  
The charachte Throws "NullReferenceException: Object reference not set to an instance of an object" on line 17... Maybe, the problem is with the charcter script? It is here:
Expand|Select|Wrap|Line Numbers
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class MovingObj : MonoBehaviour
  6. {
  7.     [SerializeField] private float speed = 2f; // скорость движения
  8.     [SerializeField] private int lives = 5; // скорость движения
  9.     [SerializeField] private float jumpForce = 15f; // сила прыжка
  10.     public int diamondsQuantity = 0;
  11.     private bool isGrounded = false;
  12.  
  13.     private ContactFilter2D gh;
  14.     private Rigidbody2D rb;
  15.     private SpriteRenderer sprite;
  16.  
  17.     private void Awake()
  18.     {
  19.         rb = GetComponent<Rigidbody2D>();
  20.         sprite = GetComponentInChildren<SpriteRenderer>();
  21.     }
  22.  
  23.     private void OnCollisionEnter2D(Collision2D c)
  24.     {
  25.         collisionWithDiamond(c);
  26.     }
  27.  
  28.     private void FixedUpdate()
  29.     {
  30.         CheckGround();
  31.     }
  32.  
  33.     private void Update()
  34.     {
  35.         if (Input.GetButton("Horizontal"))
  36.             Run();
  37.         if (isGrounded && Input.GetButtonDown("Jump"))
  38.             Jump();
  39.     }
  40.  
  41.     private void Run()
  42.     {
  43.         Vector3 dir = transform.right * Input.GetAxis("Horizontal");
  44.  
  45.         transform.position = Vector3.MoveTowards(transform.position, transform.position + dir, speed * Time.deltaTime);
  46.  
  47.         sprite.flipX = dir.x < 0.0f;
  48.     }
  49.  
  50.     private void Jump()
  51.     {
  52.         rb.AddForce(transform.up * jumpForce, ForceMode2D.Impulse);
  53.     }
  54.  
  55.     private void collisionWithDiamond(Collision2D d)
  56.     {
  57.         if (d.gameObject.tag == "Diamond") //у всех алмазов тег Diamond, сюда можно записать и тот публичный метод
  58.         {
  59.             Destroy(d.gameObject);
  60.             diamondsQuantity++;
  61.         }
  62.     }
  63.  
  64.     private void CheckGround()
  65.     {
  66.         Collider2D[] collider = Physics2D.OverlapPointAll(new Vector2 (transform.position.x, transform.position.y - 0.5f));
  67.         isGrounded = collider.Length >= 1;
  68.     }
  69. }
  70.  
How to fix it?
and yes, I know that this will update the text every second, after fixing I am going to write a public method.
Oct 2 '21 #1
0 5638

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Stan Brown | last post by:
URL: http://www.acad.sunytccc.edu/instruct/sbrown/stat/mygrades.htm CSS: http://www.acad.sunytccc.edu/instruct/sbrown/screen.css Both validate without errors or warnings under W3C validators. ...
4
by: Ken VdB | last post by:
Hi everyone, One of the things that really interested me about VS.net was that I can now create a console based app using VB. I have a number of QuickBASIC 4.5 apps which we are still using and...
2
by: gwainguard | last post by:
Hello, would you please consider the following small piece of code. using System; class Constants { public const int A = B; public const int B = 2; }
0
by: dragonguy83 | last post by:
Hi guys, i have bee around these forums alot learning so much. hopefully someone will be able to help me out. here is my setup. i have a xp pro desktop connected to a netgear wireless router that...
4
by: ramaswamynanda | last post by:
Hello, I have an application in Access where I have developed about 10 reports. These have been working for a while and produce data properly. I recently tried exporting the report, from the...
17
by: asit | last post by:
#include <stdio.h> int main() { char p='19'; ----------------- return 0; }
66
by: happyse27 | last post by:
Hi All, my html code is sno 1) and perl code is sno 2). a) I tried to print $filename and it cant print out the value, only blank was displayed, and the file could not be uploaded. And it...
11
by: dowlingm815 | last post by:
the following code is generating an error; Mircosoft Access cant find the field '|" referred to in your expression" any suggestions would be appreciated. Private Sub...
1
by: maximus tee | last post by:
hi, i'm using Python 2.5 and Windows XP. i'm wondering whether is a way to enlarge the font size when print out to CMD window. For eg: print "Hello World". It will print out with standard size in...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
0
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.
0
DizelArs
by: DizelArs | last post by:
Hi all) Faced with a problem, element.click() event doesn't work in Safari browser. Tried various tricks like emulating touch event through a function: let clickEvent = new Event('click', {...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.