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:
The charachte Throws "NullReferenceE xception: Object reference not set to an instance of an object" on line 17... Maybe, the problem is with the charcter script? It is here:
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.
Code:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class textScr : MonoBehaviour {
private MovingObj _movingObj;
private Text _diamondText;
void Start()
{
_movingObj = GameObject.Find("Square").GetComponent<MovingObj>();
}
public void Update()
{
_diamondText.text = "Diamonds: " + _movingObj.diamondsQuantity.ToString();
}
}
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingObj : MonoBehaviour
{
[SerializeField] private float speed = 2f; // скорость движения
[SerializeField] private int lives = 5; // скорость движения
[SerializeField] private float jumpForce = 15f; // сила прыжка
public int diamondsQuantity = 0;
private bool isGrounded = false;
private ContactFilter2D gh;
private Rigidbody2D rb;
private SpriteRenderer sprite;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
sprite = GetComponentInChildren<SpriteRenderer>();
}
private void OnCollisionEnter2D(Collision2D c)
{
collisionWithDiamond(c);
}
private void FixedUpdate()
{
CheckGround();
}
private void Update()
{
if (Input.GetButton("Horizontal"))
Run();
if (isGrounded && Input.GetButtonDown("Jump"))
Jump();
}
private void Run()
{
Vector3 dir = transform.right * Input.GetAxis("Horizontal");
transform.position = Vector3.MoveTowards(transform.position, transform.position + dir, speed * Time.deltaTime);
sprite.flipX = dir.x < 0.0f;
}
private void Jump()
{
rb.AddForce(transform.up * jumpForce, ForceMode2D.Impulse);
}
private void collisionWithDiamond(Collision2D d)
{
if (d.gameObject.tag == "Diamond") //у всех алмазов тег Diamond, сюда можно записать и тот публичный метод
{
Destroy(d.gameObject);
diamondsQuantity++;
}
}
private void CheckGround()
{
Collider2D[] collider = Physics2D.OverlapPointAll(new Vector2 (transform.position.x, transform.position.y - 0.5f));
isGrounded = collider.Length >= 1;
}
}
and yes, I know that this will update the text every second, after fixing I am going to write a public method.