Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Script throws NullReferenceException, even though there is a reference. how to fix?

Discussion in 'Scripting' started by serudel28, Aug 14, 2023.

  1. serudel28

    serudel28

    Joined:
    Aug 12, 2023
    Posts:
    3
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using TMPro;

    public class DamagePopup : MonoBehaviour
    {
    [SerializeField] GameObject dmgPopup; //a prefab

    public void Popup(Vector3 position, float damage)
    {
    var Clone = Instantiate(dmgPopup, position, Quaternion.identity); //clone reference
    Clone.transform.SetParent(GameObject.Find("Canvas").transform);
    Vector2 randomForce = new Vector2(Random.Range(-1f, 1f), Random.Range(5f, 10f));
    Rigidbody2D CloneRb = Clone.GetComponent<Rigidbody2D>(); //this works fine
    CloneRb.AddForce(randomForce, ForceMode2D.Impulse);
    Clone.GetComponent<TextMeshPro>().SetText(damage.ToString()); //this line throws the error
    Destroy(Clone, 2);
    }
    }
     
  2. serudel28

    serudel28

    Joined:
    Aug 12, 2023
    Posts:
    3
    nevermind. figured it out myself
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
  4. serudel28

    serudel28

    Joined:
    Aug 12, 2023
    Posts:
    3
    i saw your post already