473,387 Members | 1,579 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 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 5888

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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.