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;
  6. public class textScr : MonoBehaviour { 
  7.     private MovingObj _movingObj;
  8.     private Text _diamondText;
  10.     void Start()
  11.     {
  12.         _movingObj = GameObject.Find("Square").GetComponent<MovingObj>();
  13.     }
  15.     public void Update()
  16.     {
  17.         _diamondText.text = "Diamonds: " + _movingObj.diamondsQuantity.ToString();
  18.     }
  20. }
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;
  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;
  13.     private ContactFilter2D gh;
  14.     private Rigidbody2D rb;
  15.     private SpriteRenderer sprite;
  17.     private void Awake()
  18.     {
  19.         rb = GetComponent<Rigidbody2D>();
  20.         sprite = GetComponentInChildren<SpriteRenderer>();
  21.     }
  23.     private void OnCollisionEnter2D(Collision2D c)
  24.     {
  25.         collisionWithDiamond(c);
  26.     }
  28.     private void FixedUpdate()
  29.     {
  30.         CheckGround();
  31.     }
  33.     private void Update()
  34.     {
  35.         if (Input.GetButton("Horizontal"))
  36.             Run();
  37.         if (isGrounded && Input.GetButtonDown("Jump"))
  38.             Jump();
  39.     }
  41.     private void Run()
  42.     {
  43.         Vector3 dir = transform.right * Input.GetAxis("Horizontal");
  45.         transform.position = Vector3.MoveTowards(transform.position, transform.position + dir, speed * Time.deltaTime);
  47.         sprite.flipX = dir.x < 0.0f;
  48.     }
  50.     private void Jump()
  51.     {
  52.         rb.AddForce(transform.up * jumpForce, ForceMode2D.Impulse);
  53.     }
  55.     private void collisionWithDiamond(Collision2D d)
  56.     {
  57.         if (d.gameObject.tag == "Diamond") //у всех алмазов тег Diamond, сюда можно записать и тот публичный метод
  58.         {
  59.             Destroy(d.gameObject);
  60.             diamondsQuantity++;
  61.         }
  62.     }
  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. }
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

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. ...
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...
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; }
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...
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...
by: asit | last post by:
#include <stdio.h> int main() { char p='19'; ----------------- return 0; }
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...
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...
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...
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...
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...
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...
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...
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++...
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...
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...
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.
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.